Virtual functions
Jul 21, 2017 at 9:24pm UTC
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;
}
Jul 21, 2017 at 9:31pm UTC
> 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.
Jul 21, 2017 at 9:34pm UTC
oops.. got it...my bad!! forgot specifiers.....from java background
Last edited on Jul 21, 2017 at 9:35pm UTC
Jul 21, 2017 at 10:07pm UTC
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();
}
Jul 23, 2017 at 10:31am UTC
if you want to use pointers...consider smart pointers :D
Topic archived. No new replies allowed.