accessing variables

Started by
5 comments, last by nobodynews 13 years, 3 months ago
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
Advertisement
Why don't you just make it a CPlayer pointer to begin with?

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:

#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.

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.

C++: A Dialog | C++0x Features: Part1 (lambdas, auto, static_assert) , Part 2 (rvalue references) , Part 3 (decltype) | Write Games | Fix Your Timestep!

This topic is closed to new replies.

Advertisement