Sign in to follow this  

Base class constructor variables

This topic is 3679 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi how should I go about coding it if I wish to pass in variables to my base class constructor?
class Base
{
   int myInt;

public:
   Base(int A)
   {
      myInt = A;
   };
};

class Bar : public Base
{
public:
    Bar()
    {
       Base(10);
    }
};

Does this work? I didn't put a default Base() constructor, because I want to restrict the declaration of all Base class to fill in a int like: Base b(132); Base z; <- Will give error, hence it force user to not declare it this way Thanks

Share this post


Link to post
Share on other sites
Just to note:

class Bar
{
// ...
Bar()
{
Base(10);
}
// ...
};



This is valid syntax, it creates an anonymous Base instance with the value ten passed to its constructor. An example where you might use this syntax is adding value objects to a container, like so:

std::vector<Sphere> spheres;
spheres.push_back(Sphere(radius));

Share this post


Link to post
Share on other sites

This topic is 3679 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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