virtual function question

C

ciccio

Hi,

Ones more I have a stupid virtual function question. Assume the
following simple lines of code

class Parent {
public:
virtual Parent foo(Parent &);
virtual void bar(Parent &);
}

class Child : public Parent {
Child foo(Child &);
void bar(Child &);
}

Will foo and bar be virtually overloaded?
Or is this here a complete misconception of virtual functions?

Thanks
 
C

ciccio

Okay sorry for the waste of internet bits ... a simple test gave me the
answer.

#include <iostream>

class P {
public:
virtual P foo(P &a) { std::cout << "P::foo called" <<
std::endl; return a; }
virtual void bar(P &a) { std::cout << "P::bar called" <<
std::endl; }
virtual void print(void) {std::cout << "P::print called" <<
std::endl; }
};

class C : public P {
public:
C foo(C &a) { std::cout << "C::foo called" << std::endl;
return a; }
void bar(C &a) { std::cout << "C::bar called" << std::endl; }
void print(void) {std::cout << "C::print called" << std::endl; }
};

int main(void) {
P a, *ptr;
C c;

a.foo(a);
a.bar(a);
c.foo(c);
c.bar(c);
a.print();
c.print();

ptr = &c;
ptr->foo(c);
ptr->foo(a);
ptr->bar(c);
ptr->bar(a);
ptr->print();
};

OUTPUT
P::foo called
P::bar called
C::foo called
C::bar called
P::print called
C::print called
P::foo called
P::foo called
P::bar called
P::bar called
C::print called
 
R

Ron Natalie

ciccio wrote:
=
Will foo and bar be virtually overloaded?
Or is this here a complete misconception of virtual functions?
The term is OVERRIDING. Overloading refers to multiple definitions
of the same name, for example:
Parent::foo(int);
Parent::foo(long);
would be OVERLOADS.

And no you don't have overriding. C::foo(C&) doesn't override
P::foo(P&).

The only wiggle room you get is in the return type. The following
is allowed:

struct P {
P& foo(P&) { return *this; }
};

struct C : P {
C& foo(P&) { return *this; }
};

In this case C::foo overrides the same signature function in
main. The return type is allowed to be a pointer or reference
to the derived type and still work.
 

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,995
Messages
2,570,226
Members
46,815
Latest member
treekmostly22

Latest Threads

Top