I want to add a class directly into a new class by avoiding public inheritance. For example I have a class like
class size {
private:
int width;
int height;
public:
void set_width(int w) { width = w; }
int get_width() { return width; }
void set_height(int h) { height = h; }
int get_height() { return height; }
int get_area() { return width*height; }
};
and simply want to plug in it's functionality into a new class like this
class square : public size {
// ...
};
and can write
square s;
s.set_width(10);
s.set_height(20);
cout << "Area of the square: " << s.get_area() << endl;
But this way I'm violating the is-a rule for public inheritance. My square
isn't a size
it has-a size
. So I have to write
class square {
public:
size its_size;
// ...
};
But now my original idea of plugging the functionality of size
right into square
gets lost. I have to write
square s;
s.its_size.set_width(10);
s.its_size.set_height(20);
cout << "Area of the square: " << s.its_size.get_area() << endl;
or add several wrappers for the getters and setters of size
into square
.
Edit: I have to add: size
isn't destined to have a virtual destructor. I don't want to use size
and it's descendants polymorphically.
Edit 2: Another example: You want to write a class that provides the same interface as std::list<T>
but offers a lot more functionality than a simple free standing function can accomplish. The standard containers shoudn't be subclassed so you have to add a std::list<T>
as a member and wrap all publicly provided functions of std::list<T>
directly to your new class. That's a lot of repetitive work and error prone.
Question: Is there a possibility to add the interface of size
publicly into square
without publicly inheriting from size
. My square
shouldn't be a size
but ought to offer the same interface (next to its own parts).