virtual from Base-of-Base?

R

.rhavin grobert

guess you have ....

class Grandbase {
public:
virtual int foo();
};

class Base: public Grandbase {
/* no foo() specified here */
};

class Derived, public Base {
public:
virtual int foo();
};

my compiler gives no errors, ..but ... is it safe?
 
S

Salt_Peter

does a...

void callfoo(Grandbase* b)
{
  b->foo();

};

Derived d;
callfoo(d);

always call Derived::foo() ?

yes, and callfoo() can also be a member function of Grandbase
It'll call the appropriate virtual foo()
with respect of the type of the object calling it.
Thats still the case even if foo() is private.

#include <iostream>

class Grandbase
{
virtual int foo()
{
std::cout << "GrandBase::foo()\n";
return 0;
}
public:
int callfoo() { return foo(); }

};

class Base : public Grandbase {

};

class Derived : public Base
{
int foo()
{
std::cout << "Derived::foo()\n";
return 0;
}
};

int main()
{
Base b;
Derived d;

b.callfoo();
d.callfoo();
}

/*
GrandBase::foo()
Derived::foo()
*/

I see you passing pointers around, prefer references to constant.
Why?
If you allocate and deallocate using Grandbase* pointers, you'll get
memory leaks because your Grandbase class doesn't have a virtual
d~tor.
What you can't do is declare foo() in Grandbase pure virtual and then
attempt to create an instance of Grandbase or Base.
 
M

Marcel Müller

..rhavin grobert said:
guess you have ....

class Grandbase {
public:
virtual int foo();
};

class Base: public Grandbase {
/* no foo() specified here */
};

class Derived, public Base {
public:
virtual int foo();
};

my compiler gives no errors, ..but ... is it safe?

Same here, but if you remove the syntax error after class Derived, you
may have more luck.


Marcel
 
M

mail.dsp

guess you have ....

class Grandbase {
public:
virtual int foo();

};

class Base: public Grandbase {
/* no foo() specified here */

};

class Derived, public Base {
public:
virtual int foo();

};

my compiler gives no errors, ..but ... is it safe?

Definitely it will not give any error because Base class has also int
foo() method derived from Grandbase and it will remain virtual inside
class Base. All the derived class of Base can override int foo(). To
clear these concepts study The C++ Programming Language by Stroustrup.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top