0

I am currently preparing for an exam, by learning Polymorphism. I wrote this Programm:

#include <iostream>
#include <vector>
using namespace std;

class A {
public:
    int x = 3;

    virtual void print() { cout << 3 << endl; }
};

class B : public A {
public:
    int x = 5;

    void print() { cout << 5 << endl; }
};

int main() {
    B b;
    A a;
    vector<A> name1;

    name1.push_back(b);
    name1[0].print();
    cout<< name1[0].x << endl;

    return 0;
}

And expected an output of "5". Why does it output "3"? Shouldn't the virtual funcion in A "forward" the call to the subclass "B"?

EDIT: From the answers I got, and further research, this happened:

  • Cutting of the complete Part of Class B, becuase I copied only Class A
  • Trying to access the functions of the B Class therefore fails.

Fix:

  • Change the Code as following:

     vector<A*> name1;
    

and

name1.push_back(&b);
NoNToxic
  • 1
  • 1

0 Answers0