rewriting members of a derived class

Hi

If we derive class CB from class CA, which already has a method function CA::method, and then redefine the method, what will happen? (assuming that the method is not virtual in CA) will we get a redefinition error? or will the new definition replace that of the parent in the derived class?

Thanks a lot

Soheil
The new definition will replace that of the parent. Note that if you wanted to use polymorphism then the method should be virtual.
You mean you want to override a non-virtual method? The code will compile, but...

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
#include <iostream>

using namespace std;


struct CA {
	void method() { cout << "CA" << endl; }
};

struct CB : public CA {
	void method() { cout << "CB" << endl; }
};


struct VA {
	virtual void method() { cout << "VA" << endl; }
};

struct VB : public VA {
	void method() { cout << "VB" << endl; }
};


int main() {
	CA *ca = new CA;
	CA *cb = new CB; //note: defined as CA*, not CB*
	VA *va = new VA;
	VA *vb = new VB; //note: defined as VA*, not VB*
	
	ca->method();
	cb->method();
	va->method();
	vb->method();
	
	return 0;
}
CA
CA
VA
VB
Last edited on
Thank you very much for your good answer and example. Now I understand. So, it is possible to replcace the method in the parrent if we don't want to use polymorphism.
Topic archived. No new replies allowed.