Re: Three Classes Share Data???
On Aug 23, 11:50 pm, Immortal Nephi <Immortal_Ne...@satx.rr.com>
wrote:
First class is the base class. It has two data: m_Base1 and m_Base2.
Second class and third class are derived classes and they are derived
from first class. m_Base1 and m_Base2 are inherited into two derived
classes.
Second class has its own m_Base1 and m_Base2 and third class does the
same. I am curious. How can second class and third class share the
same m_Base1 and m_Base2?
You have a single instance of a given class.
class Base { ... };
class Derived : Base { ... };
class DerivedAgain : Derived { ... };
DerivedAgain da;
Derived& d = da;
d is a reference to the Derived portion of instance da.
Assuming that both Derived and DerivedAgain have access to Base's
members, whether you used da or d to access those is irrelevent, both
are accesing the same object.
You define second class first and enter data into m_Base1 and
m_Base2. Then, you define third class and how can you modify a
pointer to second class' m_Base1 and m_Base2.
For example:
class Base
{
Base() {}
~Base() {}
int m_Base1;
int m_Base2;
};
Your ctors above are private, try...
class Base
{
int m_Base1;
int m_Base2;
publc:
Base() : m_Base1(0), m_Base2(0) { }
Base(int b1, int b2) : m_Base1(b1)
m_Base2(b2) { }
};
class Derive1 : public Base
{
Derive1() {}
public:
Derive1() : Base(20,30) { }
~Derive1() {}
void Set()
{
m_Base1 = 20;
m_Base2 = 30;
}
Set() is not needed, and neither would it be alowed to set Base's
private parts.
void Print()
{
std::cout << m_Base1 << std::endl;
...
}
};
class Derive2 : public Base
{
Derive2() {}
~Derive2() {}
void Print()
{
// How can you do this below?
cout << "Derive1::m_Base1 -> " << Derive1::m_Base1 << endl;
cout << "Derive1::m_Base2 -> " << Derive1::m_Base2 << endl;
}
You could pass a reference to a Derived1 instance however i don't see
any logical reason.
Basicly, If you want X to do something, you don't ask Y to do it for
you.
void Print(const Derived1& r_d1)
{
r_dl.Print();
}
Which brings us back to the idea that what you really want is one
object, if that isn't your case, you have a design problem. Does it
really make sense to instantiate some type Derived1 and then
instantiate another derivative of Base just to print the former's
contents? I don't think so.
};
int main(void)
{
Derive1 d1;
Derive2 d2;
d1.Set();
d2.Print();
return 0;
}
Nephi