Yea, polymorphism only calls the function of the class that the pointer is well, pointing to.
Object Oriented is badass. It's what really got me interested in programming and I when I am forced to program procedurally I miss it dearly. Both styles have their uses and downfalls but trying to establish loose coupling in procedural programming is ridiculously challenging.
What about the const key word in the virtual function is't it wrong to use . .. also in the main () i do not find any scenario that uses const object of the class for polymorphism in practical application programming .Can some one explain as to where do you use this scenario of const object in polymorphism.
Thanks
xxx
What about the const key word in the virtual function is't it wrong to use
No, it's not wrong.
Can some one explain as to where do you use this scenario of const object in polymorphism.
constness has nothing to do with polymorphism. You make an object const to signal to the reader that it is not going to be modified in the following code (and to a lesser extent, to prevent accidental changes and give less intelligent compilers more room for optimizations).
The const keyword is only a guarantee that the function will not modify any member data of the object on which it is operating. The object on which it is operating does not need to be const, but if it were, there is no problem using that function. For instance:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
Class C
{
public:
void consFunc() const {}
void nonConstFunc {}
};
int main()
{
C c1;
const C c2;
c1.constFunc(); // OK
c1.nonConstFunc(); // OK
c2.constFunc(); // OK
c2.nonConstFunc(); // ERROR!
}
// Polymorphisum210420121146.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <vector>
usingnamespace std;
class B
{
private:
int ba;
public:
B() { }
virtualint shift( ) const { ba = 2 ; return ba; }
~B() { }
};
class D : public B
{
int ca ;
public:
D() { }
int shift( ) const { ca = 3 ; return ca; }
~D() { cout<<"\n Dectructor of d"; }
};
int _tmain(int argc, _TCHAR* argv[])
{
const B* b = new D();
cout <<b->shift();
delete b;
return 0;
}