Monday, September 9, 2013

c++ inheritance abstract function?

c++ inheritance abstract function?

I have a somewhat basic question on inheritance that i can seem to figure
out, I've done a search and not found what I was looking for so I thought
I'd ask here (not sure if title of what I'm looking for is correct).
To keep things simple I've made a bit of example code to illustrate what
I'm not getting.
Basically if I have a parent class A and two child classes B & C, where A
contains common stuff (say an id with get/set), while B & C have functions
that are class specific. If you declare a class B like: A *bObject = new
B(); how do you then access the class specific functionbObj->specific()`?
I've tried virtual but that requires both B & C to have the same function
name / prototype declared. I've also tried declaring the abstract in A,
but that requires it to be prototype to be in A.
Where am i going wrong here? any help on this, probably basic issue would
be helpful.
#include <iostream>
using namespace std;
// A class dec
class A
{
public:
A(void);
~A(void);
char id;
void setId(char id);
char getId();
};
// B class dec - child of A
class B :
public A
{
public:
B(void);
~B(void);
void sayHello();
};
//C class dec - child of A
class C :
public A
{
public:
C(void);
~C(void);
void sayGoodby();
};
//a stuff
A::A(void)
{
}
A::~A(void)
{
}
void A::setId(char id)
{
this->id = id;
}
char A::getId()
{
return this->id;
}
//b stuff
B::B(void)
{
this->setId('b');
}
B::~B(void)
{
}
// c stuff
C::C(void)
{
this->setId('c');
}
C::~C(void)
{
}
void C::sayGoodby()
{
std::cout << "Im Only In C" << std::endl;
}
// main
void main ()
{
A *bobj = new B();
A* cobj = new C();
std::cout << "im class: " << bobj->getId() << endl;
bobj->sayHello(); // A has no member sayHello
std::cout << "im class: " << cobj->getId() << endl;
cobj->sayGoodby(); // A has no member sayGoodby
system("PAUSE");
}
Thank you for your time!

No comments:

Post a Comment