Constructor

Hello,

I'm new to programming with class and I'm having some difficulties with the constructor. I have created this class

class A
{
public:
A(); //this is the default constructor
A(int x); //this is the constructor with parameters
private:
...;
}

but I was told I could make a sort of "double constructor" like this

class A
{
public:
A(int x = 0): att_(x);
private:
int att_;
}

What I understood is that: if you pass no parameter it'll put 0 into x and then into att_; But if you pass a parameter it'll put it in x and then in att_;

I want to know if this is correct or if this is wrong.
Close, try this on for size:
1
2
3
4
5
6
class A
{
    int att_;
public:
    A( int x = 0 ): att_( x ) {}
};


Do searches for "initialization list" and "default parameters" for more information.
Last edited on
Ok thanks, it works fine. But (newbie question here) was does it change if you declare att_ before public and private (like you did)
ok thanks again !
Inside a class, members default to private. Putting private members first just removes the "private:" line but has the same member access as your first example.
Ok !! I didn't know that. That actually help a lot. Thanks !
Topic archived. No new replies allowed.