Legal to override same function in different bases?


O

Old Wolf

Is the following code well-defined, and outputs foo twice?

#include <iostream>

struct Base1 { virtual void foo() = 0; };
struct Base2 { virtual void foo() = 0; };

struct Derived: Base1, Base2
{
void foo() { std::cout << "foo" << std::endl; }
};

int main()
{
Derived d;
Base1 *b1 = &d;
Base2 *b2 = &d;
b1->foo(); b2->foo();
}
 
Ad

Advertisements

G

Guest

Is the following code well-defined, and outputs foo twice?

#include <iostream>

struct Base1 { virtual void foo() = 0; };
struct Base2 { virtual void foo() = 0; };

struct Derived: Base1, Base2
{
void foo() { std::cout << "foo" << std::endl; }
};

int main()
{
Derived d;
Base1 *b1 = &d;
Base2 *b2 = &d;
b1->foo(); b2->foo();
}

All compilers I have used will do exactly as you describe (output "foo
\nfoo\n"). It makes little sense to do otherwise doesn't it ?
Sometimes, however, I would like to prevent any override.
 
A

Alf P. Steinbach

* Old Wolf:
Is the following code well-defined, and outputs foo twice?

#include <iostream>

struct Base1 { virtual void foo() = 0; };
struct Base2 { virtual void foo() = 0; };

struct Derived: Base1, Base2
{
void foo() { std::cout << "foo" << std::endl; }
};

int main()
{
Derived d;
Base1 *b1 = &d;
Base2 *b2 = &d;
b1->foo(); b2->foo();
}

Except for the issue of also including <ostream> (AFAIUI now resolved in
favor of not needed), yes.

Just to be sure I didn't overlook any speling mstake or such I ran the
code through Comeau Online and it compiled fine.

Given that there are no trivial mistakes in spelling and so on, the
effect of overriding in multiple bases is well-defined. However, that
makes it problematic to not override. In order to override some but not
all foo's it's necessary to introduce intermediate classes.

Cheers, & hth.,

- Alf
 
Ad

Advertisements

J

James Kanze

Is the following code well-defined, and outputs foo twice?
#include <iostream>
struct Base1 { virtual void foo() = 0; };
struct Base2 { virtual void foo() = 0; };
struct Derived: Base1, Base2
{
void foo() { std::cout << "foo" << std::endl; }
};
int main()
{
Derived d;
Base1 *b1 = &d;
Base2 *b2 = &d;
b1->foo(); b2->foo();
}

Yes. It's fully defined. IIRC, this is even discussed some in
Stroustrup (one of the editions, anyway). The issue, of course,
is if Base1 is actuall GraphicObject, Base2 CardDeck, and the
function "draw()".
 

Top