Register    Login    Forum    Search    FAQ

Board index » Everything




Post new topic Reply to topic  [ 21 posts ]  Go to page 1, 2, 3  Next
Author Message
 Post subject: Constructor
 Post Posted: May 12th, 2017, 1:53 am 
 

Joined: February 28th, 2013, 3:23 am
Posts: 2827
Location: Oklahoma, United States
What does a constructor do?

The constructor of a class is responsible for initializing it's data members. It can do this either in the initializer list or the function body.


What's the initializer list?

The initializer list is the part of a constructor's definition that goes between the colon : and the curly-braces {} which is the function body. The purpose of the initializer list is to initialize data members of the class at the same time memory is allocated for the class object.


What is the difference betwen using the initializer list and the function body?

As stated, the initializer list initializes members when the memory is allocated for the class object, while using the function body is a second step. By the time the function body is reached, the memory is already allocated and if none of the members were manually initialized, then they were default initialized with garbage values. This means now you must assign the data members new data in the function body, which means using the initializer list is more efficient, but there are cases where you cannot use the initializer list.


What are those cases?

When you have an array or vector you want to initialize, then you are most likely going to want to use a for loop to initialize all the elements in the array. You can't do this in the initializer list and therefore need to use the function body.


How do you call constructors from a constructor?

Use the initializer list, the same as you would initialize a data member. There is a caveat to doing this though, if you call a constructor from the initializer list, you cannot use it for any other data members.

Example:
Code:

class MyClass
{
public:
   MyClass();
   MyClass(float X, float Y, const std::string &Name)
      :
   x(X), y(Y), foo(0), bar(0)
   {}
   MyClass(int Foo, int Bar, const std::string &Name)
      :
   x(0.f), y(0.f), foo(Foo), bar(Bar)
   {}
   MyClass(float X, float Y, int Foo, int Bar, const std::string &Name)
      :
   MyClass(X, Y, Name)
   {
      // Now I have to assign Foo and Bar separately
      foo = Foo;
      bar = Bar;
   }
private:
   int foo, bar,
   float x, y;
   std::string name;
};



_________________
If you think paging some data from disk into RAM is slow, try paging it into a simian cerebrum over a pair of optical nerves. - gameprogrammingpatterns.com


Top 
 Profile  
Reply with quote  
 Post subject: Re: Constructor
 Post Posted: May 24th, 2017, 4:26 am 
User avatar

Joined: November 14th, 2014, 2:03 am
Posts: 78
I personally prefer putting the list next to the signature:

Code:
constexpr Vector3 ( const float x, const float y, const float z ) : x_ { x }, y_ { y }, z_ { z }
{
}

_________________
Zekilk


Top 
 Profile  
Reply with quote  
 Post subject: Re: Constructor
 Post Posted: May 24th, 2017, 6:07 am 
 

Joined: February 28th, 2013, 3:23 am
Posts: 2827
Location: Oklahoma, United States
cyboryxmen wrote:
I personally prefer putting the list next to the signature:

Code:
constexpr Vector3 ( const float x, const float y, const float z ) : x_ { x }, y_ { y }, z_ { z }
{
}


The only problem with that is the length of the line. My environment for instance, being visual impaired, is maxed at 100 columns, so I try to stick with the golden rule of 80 characters per line if possible. That way I get to see everything without having to scroll horizontally.

I sometimes do this though.
Code:
constexpr Vector3 ( const float x, const float y, const float z )
     : x_ { x }, y_ { y }, z_ { z }
{
}

_________________
If you think paging some data from disk into RAM is slow, try paging it into a simian cerebrum over a pair of optical nerves. - gameprogrammingpatterns.com


Top 
 Profile  
Reply with quote  
 Post subject: Re: Constructor
 Post Posted: May 24th, 2017, 8:50 am 
User avatar

Joined: November 14th, 2014, 2:03 am
Posts: 78
Also, you can totally initialize an array in the initialization list:

Code:
constexpr Set ( ) : set_{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }
{
}

Code:
Set ( ) : set_{ RandNum ( ), RandNum ( ), RandNum ( ), RandNum ( ), RandNum ( ), RandNum ( ), RandNum ( ), RandNum ( ), RandNum ( ), RandNum ( ) }
{
}

This is from the C++11 standard and is tested with Visual Studio 2015.

_________________
Zekilk


Last edited by cyboryxmen on May 24th, 2017, 9:16 am, edited 2 times in total.

Top 
 Profile  
Reply with quote  
 Post subject: Re: Constructor
 Post Posted: May 24th, 2017, 9:05 am 
User avatar

Joined: May 23rd, 2013, 3:52 pm
Posts: 1236
Location: USA
albinopapa wrote:
I sometimes do this though.
Code:
constexpr Vector3 ( const float x, const float y, const float z )
     : x_ { x }, y_ { y }, z_ { z }
{
}

this is my preferred style

(and i somehow thought that one could initialize arrays in the initializer list, as cyboryx just showed us)

_________________
always available, always on, about ~10 years c/c++, java[script], win32/directx api, [x]html/css/php/some asp/sql experience. (all self taught)
Knows English, Spanish and Japanese.
irc://irc.freenode.net/#pchili alt -- join up if ever want real-time help or to just chat :mrgreen: --


Top 
 Profile  
Reply with quote  
 Post subject: Re: Constructor
 Post Posted: May 24th, 2017, 9:16 am 
User avatar

Joined: November 14th, 2014, 2:03 am
Posts: 78
While we're at it, you can also set the default value of the member variable at the class declaration C# style.
Code:
class Set
{
public:
   Set ( ) = default;
   Set ( int ( &set ) [ 10 ] ) : set_ { set [ 0 ], set [ 1 ], set [ 2 ], set [ 3 ], set [ 4 ], set [ 5 ], set [ 6 ], set [ 7 ], set [ 8 ], set [ 9 ] }
   {
   }

   int Get( const std::size_t index ) const
   {
      return set_ [ index ];
   }

private:
   int set_ [ 10 ] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
   int useless_var_ { 12 };
};

int main ( )
{
   int arr [ 10 ] { 1, 1, 1, 1, 1, 6, 1, 1, 1, 1 };
   const Set set { arr };

   std::cout << set.Get ( 5 ) << std::endl;

   system ( "pause" );
   return 0;
}


As you can see, the initializer list overrides the default value you set in the member variable declaration.

_________________
Zekilk


Top 
 Profile  
Reply with quote  
 Post subject: Re: Constructor
 Post Posted: May 24th, 2017, 9:34 am 
 

Joined: February 28th, 2013, 3:23 am
Posts: 2827
Location: Oklahoma, United States
I've never seen this before

Code:
void Func(int( &st )[ 10 ]){}


How is this even working?

_________________
If you think paging some data from disk into RAM is slow, try paging it into a simian cerebrum over a pair of optical nerves. - gameprogrammingpatterns.com


Top 
 Profile  
Reply with quote  
 Post subject: Re: Constructor
 Post Posted: May 24th, 2017, 9:36 am 
 

Joined: February 28th, 2013, 3:23 am
Posts: 2827
Location: Oklahoma, United States
This is the code you used:
Code:
   Set( int( &set )[ 10 ] ) : set_{ set[ 0 ], set[ 1 ], set[ 2 ], set[ 3 ], set[ 4 ], set[ 5 ], set[ 6 ], set[ 7 ], set[ 8 ], set[ 9 ] }

I understand the initialization of the set_ member using the init list, the part I don't understand is the parameter list, the int(&set)[10] part.

_________________
If you think paging some data from disk into RAM is slow, try paging it into a simian cerebrum over a pair of optical nerves. - gameprogrammingpatterns.com


Top 
 Profile  
Reply with quote  
 Post subject: Re: Constructor
 Post Posted: May 24th, 2017, 9:44 am 
User avatar

Joined: November 14th, 2014, 2:03 am
Posts: 78
I guess most people who don't do metaprogramming wouldn't have much knowledge nor use for array types. When you deal with arrays, they would usually decompose into pointers. However, you need to realise that arrays are not just pointers but are their very own type. Instead of decomposing them into pointers, you can get the array itself with the array type Type( &name )[ SIZE ]. Add an & and you'll get the reference type. I use this a lot for metaprogramming with overloading and type specifications.

_________________
Zekilk


Last edited by cyboryxmen on May 24th, 2017, 9:58 am, edited 1 time in total.

Top 
 Profile  
Reply with quote  
 Post subject: Re: Constructor
 Post Posted: May 24th, 2017, 9:54 am 
 

Joined: February 28th, 2013, 3:23 am
Posts: 2827
Location: Oklahoma, United States
@Luis, yes, you can init arrays in the init list. The reason I made that statement is 1) You probably aren't going to have such small arrays. Initializing an array of 100+ items in the init list is a waste of time. 2) If it is an array of simple types, it may be reasonable, but if it's an array of user defined types with a few parameters in the constructors, still unreasonable. 3) I was heading in the right direction in the first sentence, but by the second sentence, I forgot about braced initialization.

Before C++11, it wasn't possible if the class didn't have a default constructor, but now you can use braced initialization on arrays of classes that don't have default constructors.

Code:
class MyStuff
{
public:
   MyStuff( float X, int A )
      :
      x( X ), a( A )
   {
   }

   float X()const { return x; }

   int A()const { return a; }
private:
   float x = 0.f;
   int a = 0;
};

class MyStuffContainer
{
public:
   MyStuffContainer()
      :
      stuff{ { 1.f, 0 }, { 2.f, 1 }, { 3.f, 2 }, { 4.f, 3 }, { 5.f, 4 },
      { 6.f, 5 }, { 7.f, 6 }, { 8.f, 7 }, { 9.f, 8 }, { 10.f, 9 } }
   {
   }
   const MyStuff &operator[]( int Idx )const { return *( stuff + Idx ); }
private:
   MyStuff stuff[ 10 ];
};
int main()
{
   MyStuffContainer stuff;
   for( int i = 0; i < 10; ++i )
   {
      std::cout << stuff[ i ].A() << "    " << stuff[ i ].X() << std::endl;
   }
   
   system( "pause" );
   return 0;
}

_________________
If you think paging some data from disk into RAM is slow, try paging it into a simian cerebrum over a pair of optical nerves. - gameprogrammingpatterns.com


Top 
 Profile  
Reply with quote  
Display posts from previous:  Sort by  
 
Post new topic Reply to topic  [ 21 posts ]  Go to page 1, 2, 3  Next

Board index » Everything


 
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Search for:
cron