user1010101
user1010101

Reputation: 1658

Class inheritance and upcasting in c++

This is the simple code I am dealing with to learn about inheritance down casting and up casting etc.

class A
{ public:
  void p() {cout << “A::p\n”;}
  virtual void q() {cout << “A::q\n”;}
};

class B : public A
{ public:
  void p() { cout << “B::p\n”;}
  void q() { cout << “B::q\n”;}
};

int main()
{ A* a1 = new B;
  a1 -> p();
  a1 -> q();
}

Following was my expected output

B::p
B::q

Following is the actual output

A::p
B::q

My understanding is that the class B is inheriting class A. Then in the main we create a Pointer to class A and set its reference to B. Therefore when we call function p() and q() I expected whatever was inside class B to print.

Can anyone please clarify my misunderstanding here?

Upvotes: 1

Views: 101

Answers (1)

StuartLC
StuartLC

Reputation: 107317

You'll notice the difference between the two methods is that one is marked virtual on the base class A, the other isn't:

Method q is defined as

virtual void q()

On the base class, whereas p is just

void p() 

Hence,

A* a1 = new B;
a1 -> p(); ... Uses a1's type to determine the method, statically
a1 -> q(); ... Uses virtual method table to determine the method at run time

Upvotes: 2

Related Questions