Sign in to follow this  
Wavesonics

C++ Inherited Constructors question

Recommended Posts

So I have this base class, and for one derived class I don't want to have to pass 1 of the variables that the base class's constructor requires, example:
Quote:
class A { public: A( int one, SomeStruct two ); }; class B : public A { public: B( int one ); }; B::B( int oneB ) : A( oneB, SomeStruct s = {0} ) {}
That is what I would like to do. But quite obviously GCC doesn't like it. Any ideas how how to accomplish something like this?

Share this post


Link to post
Share on other sites
Just create a temporary SomeStruct in the constructor call for A( ). That is:
struct SomeStruct
{
int j;
SomeStruct( ) : j(4) { ; }
};

class A {
public:
A( int one, SomeStruct two ) {;}
};

class B : public A {
public:
B( int one );
};

B::B( int oneB ) : A( oneB, SomeStruct( ) ) {}

int main( )
{
B(4);

return 0;
}
Compiles just fine, had to add a trivial definition for SomeStruct and A's constructor body.

-jouley

Share this post


Link to post
Share on other sites
Quote:
Original post by ToohrVyk
If it is legitimate to pass only one argument, then the interface of A should reflect this:

class A {
public:
A( int one, SomeStruct two );
A( int one );
};


no no, it is not legitimate to pass 1 to A, it is possible for B to know what should be passed to A so the client of B doesn't need to.

For instance if A is "GraphicSystem" and SomeStruct is "GraphicDeviceCaps" and B is "OpenGlSoftwareRenderer" then perhaps B knows how to create the correct SomeStruct to give A, all the time. So client code doesn't need to pass it in.

This is totally possible, totally normal, and works fine. You probably just need to use ctor syntax as jouley said.

Or if you need to have a function or something that does the work of preparing the item.


class A
{
A(int one, SomeStruct two);
}
class B
{
B(int one);
static SomeStruct GetSomeStruct();
}
B::B(int one) : A(one, GetSomeStruct())
{
}



Share this post


Link to post
Share on other sites
Yes Xai that is exactly the case.

I can't have a ctor in the struct b/c the struct is also used in a union some where and that is not valid to have.

But having a function that returns the struct works perfectly. Thanks all!

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this