Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
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 4-Oct-12 19:47pm
Comments
Mohibur Rashid at 5-Oct-12 0:52am
   
didnt you ask the same question in another thread?
pasztorpisti at 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 at 6-Oct-12 9:21am
   
The validity is automatically part of that discussion
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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.
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

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.
 
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.
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

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.
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 4

yeah its a perfectly valid ctor.
  Permalink  

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

  Print Answers RSS
0 OriginalGriff 512
1 Maciej Los 470
2 Sergey Alexandrovich Kryukov 386
3 Peter Leow 205
4 CPallini 200
0 Sergey Alexandrovich Kryukov 6,888
1 OriginalGriff 5,342
2 Peter Leow 3,962
3 Mika Wendelius 2,850
4 CHill60 2,748


Advertise | Privacy | Mobile
Web04 | 2.8.150224.1 | Last Updated 6 Oct 2012
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100