polymorphism

S

subramanian

Consider the program:

#include <iostream>
#include <string>

class A {
public:
virtual void print(void) const;
};

void A::print(void) const
{
std::cout << "A::print()\n";
return;
}

class B : public A {
public:
void print(void) const;
};

void B::print(void) const
{
std::cout << "B::print()\n";
return;
}

class C : public B {
public:
void print(void) const;
};

void C::print(void) const
{
std::cout << "C::print()\n";
return;
}

int main(void)
{
C c;
A *pa = &c;
pa->print();

return 0;
}

If I run this program the output is:
C::print()

Question:
A::print() is declared virtual. Since B::print()const is not virtual,
how does pa->print() calls C::print() ?
 
R

red floyd

subramanian said:
Consider the program:

#include <iostream>
#include <string>

class A {
public:
virtual void print(void) const;
};

void A::print(void) const
{
std::cout << "A::print()\n";
return;
}

class B : public A {
public:
void print(void) const;
};

void B::print(void) const
{
std::cout << "B::print()\n";
return;
}

class C : public B {
public:
void print(void) const;
};

void C::print(void) const
{
std::cout << "C::print()\n";
return;
}

int main(void)
{
C c;
A *pa = &c;
pa->print();

return 0;
}

If I run this program the output is:
C::print()

Question:
A::print() is declared virtual. Since B::print()const is not virtual,
how does pa->print() calls C::print() ?

You're proceeding from a faulty assumption. If a method is virtual in
the base, it's virtual in all the derived classes. B::print() const
*IS* virtual.
 

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,968
Messages
2,570,154
Members
46,702
Latest member
LukasConde

Latest Threads

Top