c++ - Polymorphism: Instance class? -
is necessary instance class class has been derived from?
if dont, can access methods anyway, in example:
#include <iostream> struct class1 { public: void func(); }; struct class2 : public class1 { // class1 c1; <-- necessary? }; void class1::func(){ std::cout << "function called" << std::endl; } int main() { class2 c2; c2.func(); }
i expected function called
.
in examples see base class being instanced in derived class: class1 c1;
. for?
is necessary instance class class has been derived from?
no, absolutely not necessary.
but in examples see base class being instanced in derived class:
class1 c1;
. for?
without knowing examples concretely deal - i.e. semantics of classes - it's not easy explain them in meaningful way. however, when create data member of type, object has sub-object of type. when do:
struct y { }; struct x { int a; std::string b; y c; };
every object of type x
have subobject a
of type int
, subobject b
of type b
, , subobject c
of type y
. accessing dot notation, done below:
y foo(); x x; std::cout << x.a; x.b = "hello, world!"; x.c = foo();
similarly, when class d
derives base class b
, contains sub-object of type b
, , implicitly inherits data members of b
:
struct b { int a; std::string b; }; struct d : b { bool c; }; // ... d d; d.c = true; d.b = "hello, base class!"; d.a = 42;
now in case, class class2
apart deriving class1
has data member of type class1
. notice, data member not base sub-object of class2
, additional member sub-object. mean?
take grain of salt, in order develop intuition, can think inheritance models "is-a" relationship, while data membership models "has-a" relationship.
so fact class2
derives publicly class1
models fact "all class2
objects class1
objects", , therefore inherit of class1
's data members. explains why objects of type class2
have base sub-object of type class1
.
on other hand, fact class2
has data member of type class1
models fact "all class2
objects contain/embed/own object of type class1
". explains why objects of type class2
have member sub-object of type class1
.
now in particular case of examples mention both of above semantics modeled @ same time - i.e. class2
both is-a , has-a class1
- no means necessary. not every thingy
is-a widget
has-a widget
.
i hope makes sense in abstract way. whether design correct or not depends on semantics of class1
, class2
objects, , on meant model, message is:
if
class2
derivesclass1
, there nothing forces addclass1
data memberclass2
.
Comments
Post a Comment