Click here to Skip to main content
15,884,298 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C++
class myClass
{
    int var1,var2;
    public:
       myClass(int a1, int b1) : var1(a1), var2(b1)
       {
       }
};


is this a valid constructor definition?

Thanks!
Posted
Comments
Mohibur Rashid 5-Oct-12 0:52am    
didnt you ask the same question in another thread?
pasztorpisti 6-Oct-12 8:11am    
The same code appeared in another thread, there the question was the difference between ctor initializer lists and assignments in ctor body.
Mohibur Rashid 6-Oct-12 9:21am    
The validity is automatically part of that discussion

Yes this is valid C++ and it compiles - I tested it. The constructor allows setting var1 and var2 when creating an object of the myClass class.
 
Share this answer
 
hi,
Yes it is a valid Ctor. This is called the initialization list, here both the variables are getting initialized "var1(a1), var2(b1)". Its more optimized and faster than assigning the values in Ctor as given below.

C#
class myClass
{
    int var1,var2;
    public:
       myClass(int a1, int b1) 
       {
          var1 =a1; 
          var2 =b1;
       }
};


Also this is the only way to assign values to the constant class variables in c++. As the constant variables has to be initialized with the value (and must not be assigned) while defining it and C++ don't allow to initialize vars inside class definition.
 
Share this answer
 
Yes, and it is exactly the same as this question[^] that you asked yesterday. Instead of posting your exam questions here, why not re-read your course notes.
 
Share this answer
 
yeah its a perfectly valid ctor.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900