C ++ inheritance, basic functions still called when overriding

I have the following two classes: one inherits from the other

Class A{
  void print(){cout << "A" << endl;}
}

Class B : A{
  void print(){cout << "B" << endl;}
}
Class C : A{
  void print(){cout << "C" << endl;}
}

Then in another class I have the following:

vector<A> things;
if (..)
  things.push_back(C());
else if (..)
 things.push_back(B());

things[0].print();

it always prints A
I would like it to print B or C depending on what thing I added to the vector
how to do it?
I tried an abstraction, but I'm not quite sure how to use it in C ++, and it does not work for me.

+3
source share
3 answers

As already mentioned, you need functions virtualto enable polymorphic behavior and cannot store classes directly by value in vector.

std::vector<A>, , , , . push_back() A, , . .

, , ( ) , vector:

std::vector<A*> things;
things.push_back(new B());
// ... use things:
things[0]->print();

// clean up later if you don't use smart pointers:
for(std::vector<A*>::iterator it = things.begin(); it != things.end(); ++it)
    delete *it;
+8

1) print() A.

2) - ; ( ) / - boost:: shared_ptr.

+8

virtual , a:

class A{
  virtual void print(){cout << "A" << endl;}
}

, ( ).

Virtual tells the compiler that the function can be overridden. When you are not using a virtual machine, it is called hiding and works differently, as you already found.

+3
source

Source: https://habr.com/ru/post/1735678/


All Articles