call parent function from overriding function in child

Mar 30, 2015 at 8:34pm
I have a class (child) that is inheriting from another class (parent). I'd like to create a function in the child class w/the same name and arguments as a function in the parent class, and have the child class call the function in the parent class before it (the child function) exits. What is the syntax to do this?

Mar 30, 2015 at 8:37pm
and have the child class call the function in the parent class before it (the child function) exits.


I dont know what this means. Please show us your code and explain further. And use code tags <> its under the format section.
Last edited on Mar 30, 2015 at 8:40pm
Mar 30, 2015 at 9:10pm
1
2
3
4
5
6
7
8
9
10
11
class parent {
public:
int test;
virtual function foo(int input) { test=input; }
}

class child : parent {
public:
int new_test;
virtual function foo(int input) { new_test=input; <call parent function foo here> }
}


so when you call child.foo, new_test and test are set to input.
Mar 30, 2015 at 9:29pm
I guess like this?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Finish
{
public:
	int input;
	Finish(){}
	~Finish(){}

	virtual void foo(){ cout << "yo" << endl; }


};



class Tester : public Finish
{
	
public:
	Finish fin;
	void foo() { cout << "Hello" << endl; fin.foo(); }
};


Edit : oh I had no idea you could just do Finish:: to access its function, thats cool thanks @Keskiverto
Last edited on Mar 30, 2015 at 9:42pm
Mar 30, 2015 at 9:33pm
No. The "fin" is a separate object. You want to call the method of this.

See http://stackoverflow.com/questions/672373/can-i-call-a-base-classs-virtual-function-if-im-overriding-it
Mar 30, 2015 at 9:38pm
keskiverto you got it, and that syntax works. thanks!
Mar 30, 2015 at 9:39pm
so i think my code should look like this:

1
2
3
4
5
6
7
8
9
10
11
12
class parent {
public:
int test;
virtual function foo(int input) { test=input; }
}

class child : parent {
public:
int new_test;
virtual function foo(int input) { new_test=input; parent::foo(input); }
}
Topic archived. No new replies allowed.