[Home]  [Edit this page]  [Recent Changes]  [Special Pages]  [Help
QbasicFAQ_AddSound » object » thunks » QbasicFAQ_SyntaxError » Zeev Suraski » CppReturn » CppSeagull » compression » midlet » CLinkingError » CppConstructor

(C++) Constructor

The method called when a class is instanciated. A class can have multiple constructors. The opposite of a constructor is a destructor.

class Example
{
  public:
  Example() 
    : mValue(0)
  {
    //Empty, as mValue is already set to zero
  }
  Example(const int& value) //Constructor #2
    : mValue(value); 
  {
    //Empty, as mValue is already set to value
  }
  const int mValue;
};
int main()
{
  Example e1;     //Calls constructor #1
  Example e2(10); //Calls constructor #2
  Example * pe1 = new Example;     //Calls constructor #1
  Example * pe2 = new Example(10); //Calls constructor #2
  delete pe1; //Calls destructor
  delete pe2; //Calls destructor
}


Define and initialize member variables in the same order [1]. Prefer initialization to assignment in constructors [2]. Never call virtual functions during construction or destruction [3,4].

Code links

References



last edited (November 11, 2006) by bilderbikkel, Number of views: 6033, Current Rev: 5 (Diff)

[Edit this page]  [Page history]  [What links here]  [Discuss this topic]  [Printer Friendly]  

Members

Username:

Password:


Register
Forgot Password?




Programmers Heaven - for .NET, Java, C/C++ and WEB Developers!
© 1996-2008 Community Networks Ltd. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited. Violators of this policy may be subject to legal action. Please read Terms Of Use and Privacy Statement for more information. Site Management by Lars Hagelin at Kontantkort.se.