Help for C++ constructor, destructor

Status
Not open for further replies.

ghosteye

Seniorius Lurkius
10
Hello Guys,
I am a beginner of C++. I am being confused about the Constructor, destructor and default constructor.
When and How Do I will understand that I have to add a constructor, destructor and default constructor ?
I know its depends on the problems. Is there any general ideas ? I read couple of tutorials but did not get it.
Is it like every time I create a object I have to have a constructor and destructor ?

Hope you guys will give me some ideas.

Thanks
 
Yes, when the defaults don't do what you need then you have to write your own.

The copy constructor of a class is used when an object of that class is constructed using another instance of the same class... which can be done explicitly (Foo foo = otherFoo;) or implicitly when an object is passed by value (E.g., void bar(Foo); bar(foo); ).

I'm not sure how useful such generic questions and answers can be to you. You'll probably gain a better understanding by writing programs and asking about specific things you don't understand in those programs. For example, you might write a class that defines various constructors and a destructor and then see if you can call each of them. Then see what happens when you delete the constructors and destructor one by one.
 
You should supply a constructor if you want or need to be able to configure your individual object instances at creation time. That depends entirely on your object and design. If your object needs some data or resources in order to do its work, one place to supply it is as arguments to a constructor. Even if you don't pass in data through constructor arguments, you still might need to initialize member variables to something other than their default values, which you should do in constructor initializer lists.

You should always supply a destructor if your object contains data or resources that need to be explicitly freed when your object's lifetime ends. Again, this depends on your object and design. If your class contains virtual methods and you intend to inherit from the class publicly in order to use derived classes polymorphically, you should supply a virtual destructor.

You should supply a copy constructor (and assignment operator) if you want your object to have value semantics. That is, if you want to be able to assign and copy them just like simple built-in types. Also depends on your design. If your objects are big and complicated and expensive to copy, or if they represent handles to unique resources and copying does not make sense, you may not want standard value semantics.
 
Status
Not open for further replies.