Click here to Skip to main content
15,884,537 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I am currently programming a simple C++ application. I downloaded some source code from a website, but i don't understand the a class declaration.

Here's the code ;
C++
class myClass
{
public:

	myClass(int sub) : main(sub) {} //what's up with this line ?
	int	main;

	int DoCalc();
};


Please, Need help !
Posted

That stuff is called the "initialization list". Read this article about it:
http://www.cprogramming.com/tutorial/initialization-lists-c++.html[^]

You could just say
C++
main = sub;

in the constructor body instead of the initializer list in case of a simple int member but sometimes only initializer lists can do the job. For example when you have a base class or a member variable whose type is a class that doesn't have a default constructor. Same is true for a reference that is the member of your class. Read the linked article that has example code for these.
 
Share this answer
 
v2
Comments
Captain Price 9-Aug-12 12:56pm    
thanks, i got it. But the syntax is really confusing.
Albert Holguin 9-Aug-12 23:45pm    
I remember the first time I saw this syntax I thought the same thing... :)
pasztorpisti 10-Aug-12 2:37am    
Yes, its confusing and ugly. But not in all languages, for an example in java you have to initialize such members in the constructor body just like you do it with every other regular member but you have to write these mandatory initializations to the beginning of your constructor body.

PS: Forgot to mention that you have to use initializer list for example to initialize a reference too if it is a member of the class.
Volynsky Alex 10-Aug-12 3:10am    
Good answer!+5!
A declaration introduces one or more names into a program. Declarations can occur more than once in a program. Therefore, classes, structures, enumerated types, and other user-defined types can be declared for each compilation unit. The constraint on this multiple declaration is that all declarations must be identical. Declarations also serve as definitions, except when the declaration:

// Declare class CheckBox.
class CheckBox : public Control
{
public:
Boolean IsChecked();
virtual int ChangeState() = 0;
};

For more information about classes and class members, see here:
http://msdn.microsoft.com/en-us/library/0kw7hsf3.aspx
http://msdn.microsoft.com/en-us/library/4a1hcx0y.aspx
http://www.cplusplus.com/doc/tutorial/classes/
It basically means that the variable main will get the value sub when the new member of myClass is created with that constructor
Note : you must be careful with these things . It resembles calling the constructor of base class
 
Share this answer
 
Comments
Captain Price 9-Aug-12 12:56pm    
ok

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