01. This Pointer

This pointer in C++ class

DesignPattern

Usages

  • How to use this pointer
  • How to check an instance is correctly created
  • How to use a function pointer of a class

Explain

Class Structure

When a class becomes an instance, the instance is allocated in memory. Code 1 is a simple example code, and Figure 1 shows how they are in memory.

// 01_C_testSimpleExample.cpp
#include <iostream>
using namespace std;

class Point
{
    int x;
    int y;

public:
    void set(int a, int b)
    {
        x = a;
        y = b;

        cout << "a: " << a << ", b: " << b << endl;

        return;
    }
};

int main()
{
    Point p1;
    Point p2;

    p1.set(10, 20);
    p2.set(30, 40);

    return 0;
}
// Compile: clang ++ -std=c++14 -o 01_C_testSimpleExample 01_C_testSimpleExample.cpp
Code 1. Simple example
a: 10, b: 20
a: 30, b: 40
p1
p1
p2
p2
x
x
y
y
y
y
x
x
void Point::set(int a, int b)
void Point::set(int a, int b)
Figure 1. How to instances are located in memory

Each instance has their own member variables in memory. However, member functions are shared among the instances. Instead, C++ translates the member functions to add this pointer, like Code 2.

// 02_N_testMember.cpp
void Point_set(Point* this, int a, int b)
{
    this->x = a;
    this->y = b;

    return;
}
// Compile: Not available
Code 2. A modified member function

How about a static member function? A static member function can be called without an instance, so it may has different mechanism. A static member function does not have an argument for this pointer, but each member variables have this. Therefore, Code 3 has an error.

// 03_N_testStaticMember.cpp
#include <iostream>
using namespace std;

class Point
{
    int x;
    int y;

public:
    static void foo(int a)
    {
        x = a;  // = this->x = a
                // However, this is not existed in this static function.
        return;
    }
};

int main()
{
    Point::foo(10);

    return 0;
}
// Compile: Not available
Code 3. A static member function with ERROR

In this case, x is converted to this->x. However, the static foo() does not have this pointer, so it cannot be compiled.

Checking an Instance is Correctly Created

Sometimes, it is necessary to check an instance is created correctly before using it. To do that, this kind of checking is used.

// 04_C_testCallCheck.cpp
#include <iostream>
using namespace std;

class Sample
{
    int data;

protected:
    int fooImpl()
    {
        cout << "foo" << endl;

        return data;
    }

public:
    int foo()
    {
        return this ? fooImpl() : 0;
    }
};

int main()
{
    Sample* p = new Sample();

    p->foo();

    return 0;
}
// Compile: clang++ -std=c++14 -o 04_C_testCallCheck 04_C_testCallCheck.cpp
Code 4. Call and check an instance is created correctly
foo

However, even though the instance is null, the instance can call a member function. Code 5 show the case.

// 05_C_testNullInstance.cpp
#include <iostream>
using namespace std;

class Sample
{
    int data;

public:
    void foo()                  // void foo(Sample* this)
    {
        cout << "foo" << endl;
    }
};

int main()
{
    Sample* p = nullptr;        // Assume that creating an instance is failed

    p->foo();                   // foo(p); -> foo(nullptr);

    return 0;
}
// Compile: clang++ -std=c++14
//          -o 05_C_testNullInstance 05_C_testNullInstance.cpp
Code 5. Null instance calls a member function

and the output of Code 5 is

foo

Therefore, this is not correct way. Since we know how a static member function works, we can use it. Code 6 is recommend way to call and check an instance.

// 06_C_testNullInstancePrevent.cpp
#include <iostream>
using namespace std;

class Sample
{
    int data;

    void fooImpl()               // void foo(Sample* this)
    {
        cout << "foo" << endl;

        return;
    }
public:
    static void foo(Sample* const p)
    {
        if (p == nullptr)
        {
            cout << "Null instance" << endl;
            return;
        }

        return p->fooImpl();
    }
};

int main()
{
    Sample* p = nullptr;        // Assume that creating an instance is failed

    Sample::foo(static_cast(p));
                                // foo(p); -> foo(nullptr);

    return 0;
}
// Compile: clang++ -std=c++14
//              -o 06_C_testNullInstancePrevent 06_C_testNullInstancePrevent.cpp
Code 6. How to prevent Null pointer instance from calling a member function
Null instance

Function Pointer of Class

A function pointer is a very useful grammar of C/C++. Code 7 shows simple example of a function pointer.

// 07_C_testFunctionPointer.cpp
#include <iostream>
using namespace std;

void foo()
{
    cout << "foo" << endl;

    return;
}

int main()
{
    void (*f1)() = &foo;

    f1();

    return 0;
}
// Compile: clang++ -std=c++14
//          -o 07_C_testFunctionPointer 07_C_testFunctionPointer.cpp
Code 7. An example of a function pointer
foo

However, a function of a class is slightly different from a normal function. Code 8 shows how to use function pointers of a class.

// 08_C_testMemberFunctionPointer.cpp
#include <iostream>
using namespace std;

class Dialog
{
public:
    static void goo()
    {
        cout << "goo" << endl;

        return;
    }

    void hoo()
    {
        cout << "hoo" << endl;

        return;
    }
};

int main()
{
    void (*fs)() = &Dialog::goo;
    fs();

    void (Dialog::*fn)() = &Dialog::hoo;
    Dialog dialog;
    (dialog.*fn)();

    return 0;
}
// Compile: clang++ -std=c++14
//              -o 08_C_testMemberFunctionPointer 08_C_testMemberFunctionPointer.cpp
Code 8. Member Function Pointer
goo
hoo

In Dialog class, there are two member functions, goo() and foo(). A difference between both is whether or not the function is static. A static function can be called without an instance. It is similar to a normal function pointer. One thing different is a class name before a function.

However, a normal member function is complicated. When a function pointer of a normal member function is declared, it requires a name of the class before a function name. Also, it requires a target instance, because an argument of this pointer is implicitly existed in a member function.

Summary

  • A member function has implicitly this pointer argument. To define and use a function pointer,
void (Dialog::*fn)() = &Dialog::hoo;
Dialog dialog;
(dialog.*fn)();
// Function pointer for class member functions
  • A static member function does not have this pointer argument. Also It can be called without a specific instance. To define and use a function pointer
void (*fs)() = &Dialog::goo;
fs();
// Function pointer for static class member functions
  • A member function can be called by null pointer instance. However, it does not have this pointer, so it cannot use any member variables.

COMMENTS

Name

0 weights,1,abstract class,1,active function,3,adam,2,Adapter,1,affine,2,argmax,1,back propagation,3,binary classification,3,blog,2,Bucket list,1,C++,11,Casting,1,cee,1,checkButton,1,cnn,3,col2im,1,columnspan,1,comboBox,1,concrete class,1,convolution,2,cost function,6,data preprocessing,2,data set,1,deep learning,31,Design Pattern,12,DIP,1,django,1,dnn,2,Don't Repeat Your code,1,drop out,2,ensemble,2,epoch,2,favicon,1,fcn,1,frame,1,gradient descent,5,gru,1,he,1,identify function,1,im2col,1,initialization,1,Lab,9,learning rate,2,LifeLog,1,linear regression,6,logistic function,1,logistic regression,3,logit,3,LSP,1,lstm,1,machine learning,31,matplotlib,1,menu,1,message box,1,mnist,3,mse,1,multinomial classification,3,mutli layer neural network,1,Non Virtual Interface,1,normalization,2,Note,21,numpy,4,one-hot encoding,3,OOP Principles,2,Open Close Principle,1,optimization,1,overfitting,1,padding,2,partial derivative,2,pooling,2,Prototype,1,pure virtual function,1,queue runner,1,radioButton,1,RBM,1,regularization,1,relu,2,reshape,1,restricted boltzmann machine,1,rnn,2,scrolledText,1,sigmoid,2,sigmoid function,1,single layer neural network,1,softmax,6,softmax classification,3,softmax cross entropy with logits,1,softmax function,2,softmax regression,3,softmax-with-loss,2,spinBox,1,SRP,1,standardization,1,sticky,1,stride,1,tab,1,Template Method,1,TensorFlow,31,testing data,1,this,2,tkinter,5,tooltip,1,Toplevel,1,training data,1,vanishing gradient,1,Virtual Copy Constructor,1,Virtual Destructor,1,Virtual Function,1,weight decay,1,xavier,2,xor,3,
ltr
item
Universe In Computer: 01. This Pointer
01. This Pointer
This pointer in C++ class
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgXvUavVsX4rYm8cgKQ8rzps7pHmmEVtkIb66G2o5KZFCfjvO96SCEUdaw_DMYzSbdVrB8XvnaKN8ljEE7EBjutI2XvsBL-2BLdijjJRIpAOEpvlhOW-hfWP3ir3wbE488AwdFEu7WKbLgO/s0/
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgXvUavVsX4rYm8cgKQ8rzps7pHmmEVtkIb66G2o5KZFCfjvO96SCEUdaw_DMYzSbdVrB8XvnaKN8ljEE7EBjutI2XvsBL-2BLdijjJRIpAOEpvlhOW-hfWP3ir3wbE488AwdFEu7WKbLgO/s72-c/
Universe In Computer
https://kunicom.blogspot.com/2017/09/01-this-pointer.html
https://kunicom.blogspot.com/
https://kunicom.blogspot.com/
https://kunicom.blogspot.com/2017/09/01-this-pointer.html
true
2543631451419919204
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS CONTENT IS PREMIUM Please share to unlock Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy