Hi! I am quite new to c++, and I have a little problem with class inheritance, function overloading and then calling the right function (is it polymorphism?).
Here are the details: there are three classes (base class A and "child" classes B and C) with the same write void (same in declaration, different body).
A pointer of the A class type can also contain B and C object addresses, but when write is called from that pointer, the code executed is the one defined in A and not the one of the actual child class; however, I need the one defined in the child.
Hope I explained my problem, but I think this code explains itself better:
#include "stdafx.h"
#include <iostream>
usingnamespace std;
class A {
public:
void write() {
cout << "A" << endl;
}
};
class B: public A {
public:
void write() {
cout << "B";
A::write();
}
};
class C: public A {
public:
void write() {
cout << "C";
A::write();
}
};
int _tmain(int argc, _TCHAR* argv[]) {
A *pointer;
pointer = new A();
pointer->write(); //outputs "A", OK
delete pointer;
pointer = new B();
pointer->write(); //outputs "A" again, I need "BA"
delete pointer;
pointer = new C();
pointer->write(); //outputs "A" for the third time, I need "CA"
delete pointer;
system("pause");
return 0;
}
What is the right way (or the best one) to achieve the result I need?
Thanks to everyone! Have a nice day!