-1

I think that I really am confused a bit on objects and what happens when you extend an object.

My goal here is to create B() by extending A() )so that I get all of A()'s functions, etc, but make B() totally self sufficient in creating itself, etc

B(), when instantiated from someplace ends up settings its color, sizing itself, settings its position, etc so that I can do something like:

B::B *b = new B:B(something in);
this -> addChild(b, 1);

So when this->addChild() it then adds and things work how I set in B()

versus:

B::B *b = new B:B(something in);
b->setPosition();
b->setColor();
...
this -> addChild(b, 1);

Is in encapsulation and inheritance?

UPDATE: So I think what is confusing me is that if:

class A : public Z {

}

class b : public Z {

}

In A:

B::B *b = new B::B()
this-> addChild(b,1)

Shouldn't this work?

Jasmine
  • 15,375
  • 10
  • 30
  • 48

1 Answers1

1

You are not extending but making a composition.

if you want to extend the class B from A (So that you get all protected and public methods in A) you need to define B as follows:

class B : public A { ... }

If you want to contain A inside B, then you should just make things clear to the reader. It doesn't matter both of your options, unless is not clear. In your case I would prefer the first one as addChild seems just one operation.

EDIT: Ok, after your edit yes it should work. But no need to put B::B unless B is inside B namespace. Just call new B(), new A():

A *a = new A(..);

Some URIs: - Prefer composition over inheritance? - http://en.wikipedia.org/wiki/Composition_over_inheritance

Community
  • 1
  • 1
Trax
  • 1,890
  • 12
  • 15
  • I just made an update and I will make a second with some very specific code – Jasmine May 06 '13 at 16:25
  • Well, actually I am trying to understand what concept I am missing and therefor I asked this question yesterday: http://stackoverflow.com/questions/16391953/cocos2d-x-creating-an-object-based-upon-cclayercolor – Jasmine May 06 '13 at 16:29
  • I'm not quite sure to understand you, but looks like you still need more info about composition and inheritance, the common two ways to "extend" an object. Check the URIs I left in my answer. – Trax May 06 '13 at 17:01