cdummie
cdummie

Reputation: 163

Inheritance and pointers of parent class pointing to child class object

So i have the following code:

#include <iostream>

using namespace std;

class Parent
{
    int x;
    public:
    Parent(){x=10;}
    void f(){cout<<x;}
};

class Child: public Parent
{
  int x;
  public:
  Child(){x=20;}
  void f(){cout<<x;}
};

int main()
{
    Parent *pp;
    Child c;

    pp=&c;

    pp->f();

    return 0;
}

As you can see, i have two classes, Parent class and Child class publicly inherited from Parent class, so i wanted to see what can i do with pointer to a parent class.

I thought that it would be possible to use pointer to the parent class and use it on a child object, as i did in main, however, whenever i run this code, it prints out 10, which is the value i have for parent class variable x, considering that i made pp to point to child object, shouldn't it call the function f() defined in the child class and therefore, it should print the value of 20. What am i missing here? Any help appreciated!

Upvotes: 0

Views: 4496

Answers (2)

nielsen
nielsen

Reputation: 7594

There are at least two problems in the code.

First, the function f() must be declared virtual at least in the Parent class (with C++11 and later it is then good practice to append the keyword override in the Child class). The function being virtual is the mechanism that makes it possible to call the Child implementation via a Parent pointer.

Second, the variable x is declared both in the Parent and the Child class. This means that the Child object has two variables called x and by default x in Child functions will refer to the x declared in the Child class (the copy in the Parent class must be public or protected to be accessible from Child and must then, because of the name overlap, be referred to via a Parent type pointer or by explicitly specifying the class as in Parent::x).

Upvotes: 1

user1810087
user1810087

Reputation: 5334

The method f has to be virtual. As a start read this reference maybe helps.

#include <iostream>

using namespace std;

class Parent
{
    int x;
    public:
    Parent(){x=10;}
    virtual void f(){cout<<x;}
 // ^^^^^^^ see this 
};

class Child: public Parent
{
   int x;
   public:
   Child(){x=20;}
   virtual void f(){cout<<x;}
// ^^^^^^^ and this
// or since C++11 with override:
// void f() override {cout<<x;}

};

int main()
{
    Parent *pp;
    Child c;

    pp=&c;

    pp->f();

    return 0;
}

Demo

Upvotes: 2

Related Questions