Having a pointer to a parent class ?

  • Thread starter Gabriel Leblanc
  • Start date
G

Gabriel Leblanc

Is it possible to have a pointer that works like this ?

class ship
|
|
-----------------
| |
| |
class cruiser class destroyer
: public ship : public ship

/////////
ship* selectedShip;
if(buttonPressed = 1)
selectedShip = &cruiser1 //Say, have a pointer to an instance of a cruiser
else
selectedShip = &destroyer1 //Say, have a pointer to an instance of a destroyer

Thanks !
 
M

Mike Wahler

Gabriel Leblanc said:
Is it possible to have a pointer that works like this ?

class ship
|
|
-----------------
| |
| |
class cruiser class destroyer
: public ship : public ship

/////////
ship* selectedShip;
if(buttonPressed = 1)
selectedShip = &cruiser1 //Say, have a pointer to an instance of a cruiser
else
selectedShip = &destroyer1 //Say, have a pointer to an instance of a destroyer

Thanks !

Sure. What have you tried?
Example:


#include <iostream>

class Ship
{
public:
virtual void what_am_I() const = 0;
};

class Cruiser : public Ship
{
public:
void what_am_I() const
{
std::cout << "I am a Cruiser\n";
}
};

class Destroyer : public Ship
{
public:
void what_am_I() const
{
std::cout << "I am a Destroyer\n";
}
};

void foo(const Ship *p)
{
p->what_am_I();
}

int main()
{
Cruiser c;
Destroyer d;
foo(&c); /* prints "I am a Cruiser" */
foo(&d); /* prints "I am a Destroyer" */
return 0;
}

Which C++ book(s) are you reading?

-Mike
 
D

Daniel T.

Is it possible to have a pointer that works like this ?

class ship
|
|
-----------------
| |
| |
class cruiser class destroyer
: public ship : public ship

/////////
ship* selectedShip;
if(buttonPressed = 1)
selectedShip = &cruiser1 //Say, have a pointer to an instance of a
cruiser
else
selectedShip = &destroyer1 //Say, have a pointer to an instance of a
destroyer

How do you *know* that the selectedShip is a cruiser or destroyer?

Assuming you have at least one virtual function in ship, something like
this would do what you want...

ship* selectedShip;
if ( buttonPressed == 1 ) // note the double '='
{
cruiser* cruiser1 = dynamic_cast<cruiser*>(selectedShip);
assert( cruiser1 );
// do stuff with cruiser1
}
else
{
destroyer* destroyer1 = dynamic_cast<destroyer*>(selectedShip);
assert( destroyer1 );
// do stuff with destroyer1
}

But I wouldn't recommend such code.
 

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
474,164
Messages
2,570,897
Members
47,439
Latest member
shasuze

Latest Threads

Top