Problem with inheritance class

Aug 8, 2018 at 4:16am
Hi everyone,

I have a problem with inheritance:

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
53
  #include <iostream>

using namespace std;

class A
{
 public:
 A(){cout << "aaa\n";}
 void foo() {cout << "A foo\n";}
 virtual void print () { cout << "A print\n";}
 ~A() { cout << "AAA\n";}
};

class B : public A
{
 public:
 void print() {cout << "B print\n";}
 ~B() {cout << "BBB\n";}
};

class C : public B
{
  public:
 C (int) {cout <<"hi\n";}
 void foo() {cout << "C foo\n";}
 void print () {cout << "C  print\n";}
};

void do_sth (A& obj)
{
 obj.foo();
 cout << "222\n";
 obj.print();
 cout << "333\n";
 A another = obj;
 cout << "888\n";
 another.print();
}

int main()
{
 A* ptA = new A;
 C* ptC = new C (5);
 cout << "hello" << endl;
 B* ptB;
 ptA = ptC;
 cout << "Now..." << endl;
 do_sth(*ptC);
 cout <<"something" << endl;
 ptB = ptC;
 delete ptB;
 return 0;
}


And the output is:
aaa
aaa
hi
hello
Now...
A foo
222
C  print
333
888
A print
AAA
something
BBB
AAA


I don't understand why the function calls "obj.call()" called the foo function of class A while the "obj.print()" called the print function of C
Last edited on Aug 8, 2018 at 4:17am
Aug 8, 2018 at 7:18am
It's a trick, kinda. Think of it like this.

C++ supports object oriented programming and procedural programming, a allows the two to be mixed.

OOP uses virtual functions and you must access the objects indirectly (using pointers or references). Procedural programming doesn't require any fancy rules.

foo() is not virtual, so the pointer or reference's foo() will always be used directly.

print() is virtual, and the actual objects print() will be used if accessed thru any pointer or reference to one of it's base classes.
Aug 8, 2018 at 7:41am
Thank you, that was very clear and concise
Topic archived. No new replies allowed.