How to get virtual functions to inherit?

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

using namespace std;

class A {
   	public:
   		int a;   	
     	A (): a(0) {} 
		virtual void f () {a = 111;}
		virtual ~A() {}
};

class B: public A {
	public:
    	int b;
    	B (): A(), b(0) {}
       	virtual void f() {b = 3;}
};


int main()
{
   	A andy;
   	cout << "andy created:" << endl;
	cout << "andy.a = " << andy.a << endl;  // 0
	B bob;
   	cout << "bob created:" << endl;
	cout << "bob.a = " << bob.a << endl;  // 0
	cout << "bob.b = " << bob.b << endl;  // 0
	cout << "andy.f() called:" << endl;
	andy.f();
	cout << "andy.a = " << andy.a << endl;  // 111
	bob.f();
	cout << "bob.f() called:" << endl;
	cout << "bob.a = " << bob.a << endl;  // 0 (NOT 111)
	cout << "bob.b = " << bob.b << endl;  // 3
	cin.get();
	return 0;
}

The same result occurs whether they are polymorphic or not. The behaviour I want is for the function f to change both the values of a and b when f is called on derived class B, i.e. I want f to both behave as it would for its parent class A and for B when called on B. How to achieve this without defining two separate functions, or pasting the entire code in A again? Of course, I actually have chains of classes with myriads of data members that I want this property for, especially since I'm constantly adding new data members (so updating the virtual functions to maintain this property is a headache, and easy to forget to do too).
Last edited on
You don't need virtual keyword in derived class.

If you want to use polymorphism, you have to use pointers.

If you want to change two variables, just change them:
1
2
//in class B
void f() { b = 3; a = 111; }

optionally(untested, I may be wrong):
1
2
//in class B
void f() {A::f(); b = 3; }
-> void f() {A::f(); b = 3; }

Yes. That is the generic method I was seeking. It works. Thanks.
Topic archived. No new replies allowed.