ClockworkKettle
ClockworkKettle

Reputation: 181

Inheritance In Default Constructor Definition

I've been learning about Design Patterns and in my implementations of Strategy Design Pattern I discovered that I couldn't declare inheritance in a class definition like so:

class Context
{
private:
    Strategy *strategy_;
public:
    Context(Strategy* strategy) : strategy_(strategy); // This line
    ~Context();
    void set_strategy(Strategy* strategy);
    void DoStuff() const;
};

By changing the default constructor to be within my class definition worked fine

Context(Strategy* strategy=nullptr) : strategy_(strategy){}

Or by removing the inheritance from the definition and defining it outside the class like so.

class Context
{
private:
    Strategy *strategy_;
public:
    Context(Strategy* strategy); // This line
    ~Context();
    void set_strategy(Strategy* strategy);
    void DoStuff() const;
};

Context::Context(Strategy *strategy=nullptr) : strategy_(strategy){} // and this line

I'm curious as to why inheritance can't be declared in the default constructor within the class definition.

Upvotes: 0

Views: 57

Answers (2)

reyad
reyad

Reputation: 1432

Sorry to say, but you've totally got it wrong. Whatever you're not doing its not inheritance at all.

Strategy design pattern is about composition. You're using composition to create strategy design pattern which is done in your code by keeping a pointer like "Strategy *strategy_" which points to a Strategy object. So, it would be right to say, you're using composition.

If there is a class A which inherits class B, in cpp we write as follows:

class A {
  // private variables write here
  int x_, y_;
  // private methods
  void somePrivateMethod() {
  }
public:
  // public variable write here
  int x, y;
  // public methods
  A() {
  }
  void somePublicMethod() {
  }
}

class B : public A {
  int u, v, w;
public:
  int z;
  B() {
  }
  void someMethodInB() {
  }
}

And for more about cpp inheritance, I would suggest you to have a look at Herbert Schild's book CPP: The complete reference books inheritance chapter.

Upvotes: 2

sweenish
sweenish

Reputation: 5202

You write one of: Context(Strategy* strategy) : strategy_(strategy) {} or Context(Strategy* strategy); in your class declaration.

That colon doesn't indicate inheritance at all here, but direct member initialization. It's a very good thing to use in C++ and I highly recommend it. But you use it when you are implementing the constructor.

Inheritance is done on the class itself:
class Foo : public Bar {}; // class Foo inherits Bar publicly

Upvotes: 1

Related Questions