i am using polymorphism and i was wondering if its possible to access certain information
im delcaring it like
CBase* Player = new CPlayer(5,tempMatrix, 100);
is there anyway to access variables that are only in CPlayer and not in CBase
Player->m_speed;
it half lets me write
CPlayer::m_speed
intellesence will allow the "::" and then gives me option for speed
accessing variables
Why don't you just make it a CPlayer pointer to begin with?
cause i wanted everything to be polymorpsm if possible , the program runs and looks better if done this way
Its possible with virtual methods:
but this is bad primer to use this.
#include <iostream>
class CBase
{
public:
virtual ~CBase() {}
virtual int GetSpeed()
{
std::cout << "CBase GetSpeed() = " << std::endl;
return 0;
}
};
class CPlayer : public CBase
{
private:
int m_speed;
public:
CPlayer()
{
m_speed = 666;
}
~CPlayer()
{
}
int GetSpeed()
{
std::cout << "CPlayer GetSpeed() = " << std::endl;
return m_speed;
}
};
int main()
{
CBase* player = new CPlayer();
std::cout << "speed = " << player->GetSpeed() << std::endl;
delete player;
player = 0;
std::cin.get();
return 1;
}
but this is bad primer to use this.
Its possible with virtual methods:
#include <iostream>
class CBase
{
public:
virtual ~CBase() {}
virtual int GetSpeed()
{
std::cout << "CBase GetSpeed() = " << std::endl;
return 0;
}
};
class CPlayer : public CBase
{
private:
int m_speed;
public:
CPlayer()
{
m_speed = 666;
}
~CPlayer()
{
}
int GetSpeed()
{
std::cout << "CPlayer GetSpeed() = " << std::endl;
return m_speed;
}
};
int main()
{
CBase* player = new CPlayer();
std::cout << "speed = " << player->GetSpeed() << std::endl;
delete player;
player = 0;
std::cin.get();
return 1;
}
but this is bad primer to use this.
is there a way to do it without virtual funtions in the base class
You could cast the pointer to a CPlayer pointer. Of course, if you're going to do that, you might as well have left it a CPlayer to begin with.
I agree with this. You are basically violating Liskov's Substitution Principle, that "derived types must be completely substitutable for their base types". But if you still want to do this, the specific cast to use would be dynamic_cast in case that wasn't clear.
You could cast the pointer to a CPlayer pointer. Of course, if you're going to do that, you might as well have left it a CPlayer to begin with.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement