Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ problems with class inheritance

Tags:

c++

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.

like image 609
Olexy Avatar asked Jan 29 '26 06:01

Olexy


1 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.

like image 164
Joseph Larson Avatar answered Jan 31 '26 23:01

Joseph Larson