Polymorphism

S

Senthil

Hi,
In the following code..

#include<iostream>

using namespace std;

struct game{
virtual void play()
{
cout<<"unknown"<<endl;
}
};

struct tennis :public game{
void play()
{
cout<<"tennis"<<endl;
}
};

void Val(game b)
{
b.play();
}

int main()
{
game *pt=new tennis;
pt->play(); // prints tennis------------>1
(*pt).play(); // prints tennis ---------> 2
Val(*pt); // prints unknown ----------> 3

return 0;
}

The line marked with 1, prints "tennis", I understand.
I expected 2 and 3 to print "unknown" , but 2 prints "tennis" and 3
prints "unknown".
In both the cases i am invoking the method on a object(not on a pointer
or reference) and i do not expect a polymorphic behaviour.
Is my understanding wrong?

Thanks,
Senthil
 
N

Neelesh Bodas

Senthil said:
int main()
{
game *pt=new tennis;
pt->play(); // prints tennis------------>1
(*pt).play(); // prints tennis ---------> 2
Val(*pt); // prints unknown ----------> 3

return 0;
}

The line marked with 1, prints "tennis", I understand.
I expected 2 and 3 to print "unknown" , but 2 prints "tennis" and 3
prints "unknown".
In both the cases i am invoking the method on a object

pt->play is a syntactic sugar for the expression (*pt).play
i.e., both of them are same as far as compiler is concerend. There is
no object slicing involved.

In third, however, you are passing "by value" which will lead to object
slicing.
 
N

n2xssvv g02gfr12930

Senthil said:
Hi,
In the following code..

#include<iostream>

using namespace std;

struct game{
virtual void play()
{
cout<<"unknown"<<endl;
}
};

struct tennis :public game{
void play()
{
cout<<"tennis"<<endl;
}
};

void Val(game b)
{
b.play();
}

int main()
{
game *pt=new tennis;
pt->play(); // prints tennis------------>1
Correct via base class of tennis object pointed to by pt
(*pt).play(); // prints tennis ---------> 2
Correct via base class of tennis object dereferenced from pointer pt
Val(*pt); // prints unknown ----------> 3
Correct base clase object passed by value hence no longer part of a
descendant class,(note if it is passed by reference, which I prefer,
tennis would be printed).
return 0;
}

The line marked with 1, prints "tennis", I understand.
I expected 2 and 3 to print "unknown" , but 2 prints "tennis" and 3
prints "unknown".
In both the cases i am invoking the method on a object(not on a pointer
or reference) and i do not expect a polymorphic behaviour.
Is my understanding wrong?

Thanks,
Senthil
JB
 

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

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,141
Latest member
BlissKeto
Top