OOP constructor problem

Hello

I have the following code (here is just the "interesting" part):

1
2
3
4
5
6
7
8
9
class A{ 
   int x;
   public: 
     A(int i=0):x(i) {}
     int get_x() { return x; }
     int& set_x(int i){ 
        x=i;
     }
};


at line 6: A(int i=0):x(i) {}
I don't understand what ":x(i)" means
A is a constructor with one parameter, right?
x is a variable, so is x(i) a constructor? there is no class called x...
it shouldn't be equivalent with x=i, because this work only when it is used in the same time with declaration (int x(i);)
So...i also know that ":" is used when extending another class, but i don't get the meaning here.

Sorry if my post is too hard to follow. In a few words: what does line 6 does?
All line 6 does is call the constructor of x with a parameter of i. You can also do this for multiple variables:
1
2
3
4
5
6
7
8
9
class A{ 
   int x, y;
   public: 
     A(int i=0):x(i), y(1) {}
     int get_x() { return x; }
     int& set_x(int i){ 
        x=i;
     }
};


By the way, your last function doesn't return anything. You should probably change it to one of:
1
2
3
     int& set_x(){ 
        return x;
     }

or
1
2
3
     void set_x(int i){ 
        x=i;
     }

Depends on what you want to use the code for.
closed account (zb0S216C)
Elena wrote:
I don't understand what ":x(i)" means (sic)

That's your classes initializer list[1]. Your initializer list calls the constructor of each member within the list. For example:

1
2
3
4
5
6
7
8
class SIMPLE
{
    public:
        SIMPLE( void ) : Member( 0 ), Member_2( 1 )
        { }

        int Member, Member_2;
};

Here, the parentheses after Member within the initializer list, is you explicitly calling the constructor of Member's type-specifier (in this case, int). The order of the members within the initializer list must be the exact same as the order your declared them. Just because a specific object isn't a class, it doesn't necessarily mean that it doesn't have a constructor and destructor (all types have both of these by default).

Elena wrote:
A is a constructor with one parameter, right? (sic)

Correct.

Elena wrote:
x is a variable, so is x(i) a constructor? there is no class called x... (sic)

Variables within classes are referred to as members. x isn't a class, it's an int object (see my above paragraph).

References:
[1]http://www.cprogramming.com/tutorial/initialization-lists-c++.html



Wazzak
Last edited on
Thanks you very much for your replies!

@dax, yes, there it was a mistake i forgot to fix. Anyway i didn't wanted this program to do anything, just to learn on it:)
@Framework, your reply was really useful to me, for the kewords "Initialization Lists". that's at the ending of the book i'm reading, i didn't get there yet:D
Last edited on
Topic archived. No new replies allowed.