Computer Language/C++

[C++] Reference Relation of Object Pointer

정우섭 2020. 3. 27. 00:30

object pointer variable

 

Think about, what if a base class's pointer points a derived class object. 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
using namespace std;
 
class Person
{
public:
    void Sleep(){
        cout<<"Sleep"<<endl;
    }
};
  
class Student : public Person
{
public:
    void Study(){
        cout<<"Study"<<endl;
    }
};
 
class ScholarStd  : public Student
{
public:
    void Receive_Scholar(){
        cout<<"Work"<<endl;
    }
};
 
int main(void)
{
    Person* p1=new Person;
    Person* p2=new Student;
    Person* p3=new ScholarStd ;
 
    p1->Sleep();
    p2->Sleep();
    p3->Sleep();
    
/*
    p1->Sleep();            //   (o)
    p1->Study();             //   (o)
    p1->Receive_Scholar(); //   (o)
 
    p2->Sleep();            //   (o)
    p2->Study();             //   (o)
    p2->Receive_Scholar(); //    (x)
 
    p3->Sleep();            //   (o)
    p3->Study();            //    (x)
    p3->Receive_Scholar(); //    (x)
*/
    return 0;
}
 

 

Person* variables can point every derived classes.

 

(So you can dinamically allocate in derived class at line31 and line32)

 

But Person* can only handle Person class members.

 

And most important thing of this idea is that

 

if you add a direct and indirect derived class, it doesn't make any change to the handler class

 

 

Overriding of Function & Type of Pointer

 

To begin, let's predict the result of this code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
using namespace std;
 
class AAA
{
public:
    void ABC(){
        cout<<"AAA is called"<<endl;
    }
};
  
class BBB : public AAA
{
public:
    void ABC(){
        cout<<"BBB is called"<<endl;
    }
};
 
class CCC  : public BBB
{
public:
    void ABC(){
        cout<<"CCC is called"<<endl;
    }
};
 
int main(void)
{
    CCC* c = new CCC;
    BBB* b = c;
    AAA* a = b;
 
    a->ABC();
    b->ABC();
    c->ABC();
 
    delete c;
 
    return 0;
}
 
 

 

The result is..

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 
 
 
AAA is called
BBB is called
CCC is called
 

 

Let's look at line35.

 

"b->ABC();"

 

The compiler think this code as

 

"Type of b is BBB*, so the object of this pointer is overrided ABC(). Then let's call BBB's function the ABC()"

 

It is not wrong to know this code just like

 

"Using AAA* calls AAA member, BBB* calls BBB member, and CCC* calls CCC member"

 

But you should know how C++ complier works.

 

 

 

 

 

 

 

 

[참고자료]

- 윤성우의 열혈 C++ 프로그래밍