ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
Constructors are the way to create new instances of a class. They have the same name as the class and can take arguments, but they don't have to. If you do not provide a constructor, the compiler gives you a default one for free. The only thing a default constructor will do is create a new object of that class; it will not initialise any of the member variables. If you do write any constructor, a default constructor won't be provided, so if you need one that takes no arguments, you'll have to write one.
Suppose you have a class Cat and when you create a Cat, you'd like to set it's age. You can do that by adding a constructor that takes an integer parameter:
Code:
class Cat
{
public:
Cat(int age);
private:
int itsAge;
};
You could then write the implementation as
Code:
Cat::Cat(int age):itsAge(age) {}
The bit after the single colon is the initialisation stage, you can initialise any number of member variables here, separated by commas. In this example, an equivalent way of initialising itsAge would be
Code:
Cat::Cat(int age)
{
itsAge = age;
}
Both work, but my book (and probably yours too as they're written by the same author) say you should initialise itsAge in the initialisation.
Constructors can be overloaded and all that means is, you can have multiple constructors that can take different arguments:
Code:
class Cat
{
public:
Cat(); // default constructor
Cat(int age, int weight):itsAge(age), itsWeight(weight) {}
Cat(int age) { itsAge = age; }
private:
int itsAge;
int itsWeight;
};
Does that help a bit? If not, tell us which bits you aren't understanding.
Distribution: Ubuntu, Debian, Various using VMWare
Posts: 2,088
Rep:
Constructors are used to create an object, and (usually) to do some initialisation. They have the same name as the class, and are called when you create a new object.
For example, using Java:
Code:
Date d = new Date();
Where I have a Date class, and I want an instance of it called d. The above statement will call the default constructor:
Code:
public class Date
{
//First some variables
private int dayOfWeek;
private int weekOfYear;
private int year;
//And the default constructor
public void Date()
{
dayOfWeek=0;
weekOfYear=0;
year=0;
}
}
You can have other constructors that take arguments, such as values to store in the Date Class
Distribution: Ubuntu, Debian, Various using VMWare
Posts: 2,088
Rep:
Quote:
Originally posted by Nylex If you do not provide a constructor, the compiler gives you a default one for free. The only thing a default constructor will do is create a new object of that class; it will not initialise any of the member variables.
It has been well drilled in to me that you ALWAYS INITIALISE VARIABLES. Never trust a compiler to do it for you, since if you initialise them, you know what is stored there. This is particularly so with C / C++, since not all compilers are the same.
Originally posted by IBall It has been well drilled in to me that you ALWAYS INITIALISE VARIABLES. Never trust a compiler to do it for you, since if you initialise them, you know what is stored there. This is particularly so with C / C++, since not all compilers are the same.
--Ian
You mean because some compilers may put whatever was in the memory address before you defined the varialbe into the variable?
If I take out the (5) parameter in Cat Frisky(5); it doesn't compile, how come?
So a constructor is just another accessor function that lets you free up the memory when you have finished?
I would like to learn a bit more about constructors before I go on to the next chapter, does anyone know of any good resourses/tutorials on constructors and deconstructors?
Also what would be the syntax of declaring and then defining a class method that was inline and const?
#include "CAT.hpp"
Cat::Cat(int initialAge){ //constructor
itsAge = initialAge;
}
Cat::~Cat()
{
}
//Create a cat, set its age have it meow tell us its age then meow again.
int main()
{
Cat Frisky(5); //Create Frisky the cat, which is an instance of the
//cat class.
Frisky.Meow();//Have it meow
cout<<"Frisky is a cat who is ";
cout<<Frisky.GetAge();
cout<< " years old.\n";
Frisky.Meow();
Frisky.SetAge(7);
cout<<"Now Frisky is ";
cout<<Frisky.GetAge()<< " years old.\n";
cin.get();
cin.get();
cin.get();
return (0);
}
Distribution: Ubuntu, Debian, Various using VMWare
Posts: 2,088
Rep:
Quote:
If I take out the (5) parameter in Cat Frisky(5); it doesn't compile, how come?
You don't have a default constructor. If you try to create an object without passing arguments to the constructor you have, it won't compile because it is expecting an argument.
It is "Good Programming Practice" to always have a default constructor, even if you don't intend to use it. I have modified your program to include a defualt constructor, and create two Cat Objects, one using the default constructor, and the other taking itsAge as an argument.
#include "cat.hpp"
/*This defines the constructors*/
Cat::Cat( void)
{
itsAge=0;
}
Cat::Cat(int initialAge)
{
itsAge = initialAge;
}
Cat::~Cat()
{
}
//Create a cat, set its age have it meow tell us its age then meow again.
int main()
{
/*Create too cats, one Frisky, one Cuddles :)*/
Cat Frisky;
Cat Cuddles(5);
Frisky.Meow();//Have it meow
cout << "Frisky is a cat who is " << Frisky.GetAge() << " years old.\n";
Frisky.Meow();
Frisky.SetAge(7);
cout<<"Now Frisky is " << Frisky.GetAge() << " years old.\n";
cout <<"Cuddles is a cat who is :" << Cuddles.GetAge() << "years old.\n";
Cuddles.Meow();
Cuddles.SetAge(23);
cout<<"Now Cuddles is " << Cuddles.GetAge() << " years old.\n";
return (0);
}
Can you tell me what this statement would be used for in a real program Cat Cuddles(5);. With the Cuddles(5) does that mean that you actually assigned 5 to the object?
I mean why would I want to do that if I was making a real program?
Also what would be the syntax of declaring and then defining a class method that was inline and const?
Code:
class className
{
public: // assuming you wanted public access to it
return_type method_name(parameters) const { // do stuff }
}
Quote:
Originally posted by InvisibleSniper Can you tell me what this statement would be used for in a real program Cat Cuddles(5);. With the Cuddles(5) does that mean that you actually assigned 5 to the object?
He has a constructor that takes an int and uses that int to set the Cat's age. The statement "Cat Cuddles(5);" says make a new Cat and set his age to 5. You can see that in the implementation of the constructor:
Not quite sure what you're asking. The constructor name is the same as the name of the class. If you want to make an object of type Cat, you'd write "Cat" followed by any legal variable name, so for example, Cuddles is fine.
Code:
Cat Cuddles;
The constructor and destructor go in the class definition, eg.
Code:
class Cat
{
public:
Cat();
~Cat();
// other stuff
};
If you do declare them like this, then you have to write a definition as in
Code:
Cat::Cat()
{
// code here
}
If you do not want to use any statements in the body of the constructor/destructor, you can just use
Code:
class Cat
{
public:
Cat() {}
~Cat() {}
// other stuff
};
So a contructor, put simply initilizes an object? I mean I can use an accessor function to initilise variables without using a constructor, so why would I want to use a constructor?
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.