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();
}
 
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
 
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()".
 

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