Virtual functions

do_nothing() is pure virtual. So when I create an pointer of derived and point it to an derived_1 object and then do do pointer->do_nothing() derived_1 do_nothing should be called right?

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

using namespace std;

class demo
{
	void virtual do_nothing()  = 0;
};

class derived: public demo {

};

class derived_1 :public derived {
	void do_nothing() {
		cout << "DO NOTHING" << endl;
	}
};

int main()
{
	derived* d = new derived_1;

        //Why cant I do this??
	d->do_nothing();
	

	return 0;
}
> Why cant I do this??
your code doesn't compile.
the compiler gives you an error message, read it. If you don't understand the error message, then post it verbatim and we will explain it.
oops.. got it...my bad!! forgot specifiers.....from java background
Last edited on
from java background

That explains the memory leak

To fix the accessibility issue, either change demo to struct:

1
2
3
4
struct demo
{
	void virtual do_nothing()  = 0;
};

or add public: in class demo before the declaration of do_nothing:
1
2
3
4
5
class demo
{
 public:
	void virtual do_nothing()  = 0;
};


Note you don't need to touch derived, some programmers with Java background get surprised by that.


To fix the memory leak, avoid the keyword new. You don't really need it in C++. For example, that main function could look this way:
1
2
3
4
5
6
int main()
{
    derived_1 d1;
    derived& d = d1;
    d.do_nothing();
}



if you want to use pointers...consider smart pointers :D
Topic archived. No new replies allowed.