inheritance shared attribute
Dec 7, 2012 at 1:25pm UTC
Hi boys.
I have base class A and i need inherit from class A to class B1 and class B2.
class A may have shared attributes for B1 B2?
I do not want a static attributes.
THX
Very sorry for my english
Dec 7, 2012 at 4:07pm UTC
You aren't leaving us much to go on, but inheritance in C++ is simple:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
#include <iostream>
class A {
public :
int getNumber();
int myNumber;
};
class B1 : public A {
public :
int getNumber(); // Allows getNumber definition to be changed
};
class B2 : public A {
public :
int getNumber();
};
int A::getNumber() {
return myNumber;
}
int B1::getNumber() {
if (myNumber > 0)
return myNumber;
return 0;
}
int B2::getNumber() {
if (myNumber < 0)
return myNumber;
return 0;
}
int main() {
A anyNumber;
B1 posNumber;
B2 negNumber;
anyNumber.myNumber = posNumber.myNumber = negNumber.myNumber = 25;
std::cout << anyNumber.getNumber() << " " << posNumber.getNumber()
<< " " << negNumber.getNumber() << "\n" ;
anyNumber.myNumber = posNumber.myNumber = negNumber.myNumber = -25;
std::cout << anyNumber.getNumber() << " " << posNumber.getNumber()
<< " " << negNumber.getNumber() << "\n" ;
return 0;
}
Last edited on Dec 7, 2012 at 4:07pm UTC
Topic archived. No new replies allowed.