A Short Guide to C++ class inheritance

From Wikiid
Jump to: navigation, search

When you declare one class as 'derived' from another, there are several interesting things you can do.

Consider this:

 class MyBaseClass
 {
 public:        int x ;
       int getVal () { return x ; }
 } ;
 class MyFirstDerivedClass : public MyBaseClass
 {
 public:
       int y ;
       int getVal () { return y ; }
 } ;
 

If we write this:

 MyFirstDerivedClass X ;
 X.x = 6 ;
 X.y = 7 ;
 cout << X.getVal() ;

...what will it print?

Since X is a MyFirstDerivedClass - it will use the MyFirstDerivedClass version of 'getVal()' - so the answer is '7'. Simple enough - right?

But add this:

 MyBaseClass *Y = & X ;
 cout << Y.getVal() ;

...and what happens?

The trouble is that Y is a pointer to a base class - and the compiler doesn't know that it's actually pointing to a derived class. So it calls the base class member function - and that returns '6' - not '7'.

Well, that's not very nice! To "fix" this, we have to make a "virtual" function - here is the syntax:

 class MyBaseClass
 {
 public:        int x ;
       virtual int getVal () { return x ; }
 } ;
 class MyFirstDerivedClass : public MyBaseClass
 {
 public:
       int y ;
       virtual int getVal () { return y ; }
 } ;
Personal tools