Jump to content
  • Advertisement
Sign in to follow this  
littlekid

Base class constructor variables

This topic is 3894 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
Advertisement
Initializer lists.

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

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

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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!