Main Content

Null this-pointer calling method

this pointer is null during member function call

Description

This check on a this pointer dereference determines whether the pointer is NULL.

Examples

expand all

#include <stdlib.h>
class Company {
 public:
  Company(int initialNumber):numberOfClients(initialNumber) {}
  void addNewClient() {
    numberOfClients++;
  }
 protected:
  int numberOfClients;
};

void main() {
 Company* myCompany = NULL;
 myCompany->addNewClient();
}

In this example, the pointer myCompany is initialized to NULL. Therefore when the pointer is used to call the member function addNewClient, the Null this-pointer calling method produces a red error.

Correction — Initialize pointer with valid address

One possible correction is to initialize myCompany with a valid memory address using the new operator.

#include <stdlib.h>
class Company {
 public:
  Company(int initialNumber):numberOfClients(initialNumber) {}
  void addNewClient() {
    numberOfClients++;
  }
 protected:
  int numberOfClients;
};

void main() {
 Company* myCompany = new Company(0);
 myCompany->addNewClient();
}

Check Information

Group: C++
Language: C++
Acronym: NNT