Class inheritance and function overloading

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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include "stdafx.h"
#include <iostream>
using namespace 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!
Last edited on
You need to declare write() to be a virtual function in A, otherwise you are simply hiding the functions in the derived classes.
modify class A change the function to
 
virtual void write() 


http://cpp.sh/9n3c
Last edited on
Topic archived. No new replies allowed.