C++ problems with class inheritance

Viewed 116

I have base class with some variables and functions and multyply child classes. I want to minimaze amount of code required in child classes as much as possible.

Example of my code:

#include <iostream>

class base{
public:
   int a = 10;
   int b;
   void print()
   {
      std::cout << a <<std::endl;
   }
};

class child: public base
{
   public:
      int a;
};

int main()
{
    child ch;
    ch.a = 20;
    ch.print();

}

As result number 10 was printed, that means base class variable a was used, but i need to use child class variable if it exists. So expected output for this example is 20.

3 Answers

It is a significantly major mistake to override variables from the base class in your child class. This is going to bite you back just so amazingly badly.

What is happening is that ch.a is from the child class (the overwritten version), but the print function is part of the base class, so it's going to print that version.

If there's some reason to do this (I can't think of a single one), then you could typecast ch to the base class before assigning. Something like this:

(static_cast<base>(ch)).a = 20;

But the better choice is to never, never NEVER overload variable names.

I want to minimaze amount of code required in child classes as much as possible.

Well, inheritance is just for that, you have a member with name a in the base case, so using inheritance you'll already have that member also in the child class, what's the point of declaring new variable with the same name?

Why it won't ever use child class' a is because all member functions have implicit this pointer as an argument, and the type of this is the class for which you have the member function, so in this case print function "actual" declaration is

void print(base* this);

Thus, in print function you have a pointer to the base class object and that pointer will see only members from that class.

You can overshadow print function in child class and use this pointer to access a of child class there.

class child: public base
{
    public:
    int a;
    void print(){
        std::cout << this-> a << '\n';
    }
};
Related