Reputation: 20790
I have a simple Object-Components
design. Something like:
class Object1 : public Object
{
Component1 _comp1;
Component2 _comp2;
...
ComponentN _compN;
};
Is it possible to expose as public:
methods of Objects1
some methods from ComponentK
without creating a method in Object1
that calls internally ComponentK
method?
I need a simple way of doing this because it's quite annoying to write a function every time I want to expose some ComponentK
method.
Upvotes: 5
Views: 2479
Reputation: 11
You can return a pointer to the members; the pointer will be owned by the caller and can be deleted without affecting the class member:
// Example program
#include <iostream>
#include <string>
class Member {
private:
int size = 10;
public:
int getSize() {
return size;
};
};
class MemberContainer {
private:
Member member;
public:
Member * getMember () {
return &member;
};
};
int main()
{
MemberContainer memberContainer;
Member * memberPtr = memberContainer.getMember();
std::cout << memberPtr->getSize() << std::endl;
memberPtr = nullptr;
delete memberPtr;
Member * anotherMemberPtr = memberContainer.getMember();
std::cout << anotherMemberPtr->getSize() << std::endl;
}
This will output:
10
10
Upvotes: 0
Reputation: 171127
Not directly, no. You could use private inheritance to inherit from the components instead of aggregating them (note that private inheritance does not express is-a), and then publish some of their member functions by using
. Something like this:
class Object1 : public Object, private Component1, private Component2, ..., private ComponentN
{
public:
using Component1::function1();
using Component1::function2();
...
using ComponentN::functionM();
};
I'm not saying it's necessarily the best way to do it, but it's a way.
Upvotes: 14