answersLogoWhite

0


Best Answer

Without a copy constructor the only way to copy an object would be to instantiate a new object (or use an existing object) and then assign another object's value to it. However, it would be very odd indeed to have a copy assignment operator without a matching copy constructor. If you have one, you must have both. If you do not need to copy an object of a particular class, however, you can simply delete both the copy constructor and the copy assigment operator for that class. Any attempt to copy or copy assign would then result in a compile-time error.

User Avatar

Wiki User

9y ago
This answer is:
User Avatar
More answers
User Avatar

Wiki User

11y ago

Even if you don't declare a copy constructor, one is generated for you by the compiler. However, the compiler-generated copy constructor only performs a member-wise (shallow) copy of the members. This will prove disastrous if the class contains a non-static pointer variable that points to memory allocated by the class instance. A shallow copy will copy the pointer, but will not copy what it points to, resulting in two or more instances "owning" the same memory. Thus if you destroy one instance (which should rightly release the memory) you will invalidate all copies of that instance, which then invalidates the program.

To avoid this, you must implement your own copy constructor to ensure all member pointers are deep-copied, so each instance "owns" separate memory locations.

Other advantages of implementing your own copy constructor include private copy constructors (where the implementation body is empty), or when you want to provide trace code to keep track of copies. You might do this to alert you when a pass-by-value has been called inadvertently (resulting in an unwanted copy).

This answer is:
User Avatar

User Avatar

Wiki User

8y ago

* A constructor is called when you want to create a new instance of a class. A destructor is called when you want to free up the memory of an object (when you delete it). * A constructor constructs the value of an object . A destructor destructs the value created by the constructor for the object. * Another differentiation is their syntax's : constructor : (Arguments)

{

//body of constructor.

} destructor : ~() { }
The basic difference between constructor and destructor is constructor is called during the beginning of the program whereas the destructor is called at the end of the program.The former allocates memory whereas the later removes the memory.The constructor can be overloaded however the destructor cannot be overloaded.

This answer is:
User Avatar

User Avatar

Wiki User

14y ago

Discussing advantage and disadvantage is kind of a moot point; if you use a C++ class, it has both a constructor and destructor. If you don't need to do anything when a class goes out of scope, you can have an empty destructor; no problem!

The destructor is always called whenever a class goes out of scope, no matter how it happens, including an exception case, the destructor is guaranteed to be called.

A very simple example of using a constructor and destructor to ensure clean programming is the case of acquiring and releasing a semaphore. You can create a simple class that consists solely of a constructor that acquires the semaphore, and a destructor that releases it. Instantiating this class automatically does the acquire, and when it goes out of scope, even if it's because of an exception, the mutex is released. That means there is no way you can possibly forget to release the semaphore; it happens automatically. What could be better than that?

This answer is:
User Avatar

User Avatar

Wiki User

10y ago

The purpose of a destructor is to allow a class to clean up any resources it has consumed as soon as an object of the class falls from scope. There are no disadvantages to having a destructor, since all classes must have one whether you define your own or not.

This answer is:
User Avatar

User Avatar

Wiki User

12y ago

If you do not declare a copy constructor, the compiler will generate one for you. However the generated copy constructor only performs a shallow-copy (member-wise copy). This is fine for most values, but if the class contains pointers to allocated memory that would result in two separate classes pointing at the same memory. If the memory was allocated outside of the class (is not owned by the class), this is generally OK. But if the memory is owned by one of the classes, destroying either class would invalidate the other. Therefore you must declare a copy constructor and perform a deep-copy of the memory so that each copy owns its own data.

This answer is:
User Avatar

User Avatar

Wiki User

12y ago

The default copy constructor is generated by the compiler when one is not declared. The implementation makes a member-wise copy (a shallow copy) of the class members. For many classes this is adequate.

However, if your class contains pointer member variables and the memory they point to is allocated within the class itself, then those pointers must be deep copied. If they are shallow copied, then you will end up with two separate instances of the class pointing at the same memory. Thus when one instance is destroyed, the other is immediately invalidated. Deep copying ensures both instances point to their own memory allocations. To perform a deep copy you must include a user-defined copy constructor. You will also have to perform a member-wise copy of all the non-pointer member variables.

Note that if pointers are allocated memory outside of the class (the memory doesn't belong to the class), a shallow copy is fine. However, the onus is upon you, the programmer, to ensure the allocated memory remains in a valid state during the entire life-cycle of all the class instances pointing at the same memory.

This answer is:
User Avatar

User Avatar

Wiki User

11y ago

The only purpose of a constructor is to initialise an instance of your class in a controlled manner. The compiler generated constructors are not guaranteed to perform a controlled initialisation, particularly if your class allocates dynamic memory to its member variables, thus it is in your best interest to declare your own default and copy constructors to ensure correct initialisation. moreover, the default constructor access is public, so if you want to override this you must declare your own constructors. There are no disadvantages in declaring your own constructor.

The destructor gives your class one final chance to clean up any dynamic memory allocated to its members. Again, it is in your interest to declare your own destructor but, again, there are no disadvantages in declaring your own destructor.

This answer is:
User Avatar

User Avatar

Wiki User

12y ago

gfyio

This answer is:
User Avatar

User Avatar

Anonymous

Lvl 1
3y ago

Plz tel me disadvantages of destructor in c++

This answer is:
User Avatar

Add your answer:

Earn +20 pts
Q: What are the advantages of constructor and destructor?
Write your answer...
Submit
Still have questions?
magnify glass
imp
Continue Learning about Engineering

Constructor cannot be virtual but destructor can be virtual justify?

bcoz constructor cant be invoked


What is the difference between the constructor to and destructor?

Functions and Constructors are similar in many ways. They can have arguments, they can have any amount of code, they can access the class's variables etc. the only difference is that a method in java needs to mandatorily have a return type but a Constructor in java cannot have a return type. It always creates and returns an object of the class for which it is the constructor. You cannot return a value from a constructor explicitly and if you try to do that, the compiler will give an error. The system knows that the purpose of the constructor is to create an object of the class and it will do the same irrespective of whether you declare a return type or not.


A method that is automatically called when an instance of a class is created?

The constructor of a class is automatically called when an instance of the class is created (using new in C++). The constructor method has the same name as the class that it is a part of. Constructors have no type and do not return anything. Similarly, the destructor is automatically called when the instance of the class is destroyed. The destructor is the same name as the class and is preceded by a tilde (~) For example: class Example { public: Example() // Constructor { printf("Object created\n"); } ~Example() // Destructor { printf("Object destroyed\n") } }; int main() { Example* x = new Example(); // Creates object, calls constructor delete x; // Calls destructor, deletes object return 0; }


Which class methods does the compiler generate automatically if you don't provide them explicitly?

Default constructor: X()Copy constructor: X(const X&)Copy assignment operator: X& operator=(const X&)Move constructor: X(X&&)Move assignment operator: X& operator=(XX&)Destructor: ~X()By default, the compiler will generate each of these operations if a program uses it. However, if the programmer declares any constructor for a class, the default constructor for that class is not generated. If the programmer declares a copy or move operation, no copy, move or destructor is generated. If the programmer declares a destructor, no move operation is generated (a copy constructor is generated for backward compatibility).We can also suppress generation of specific operations with the =delete pseudo-initialiser:class X {public:X (const X&) =delete; // suppress the compiler-generated copy operationsX& operator=(const X&) =delete;// ...};


Parameterized constructor in c plus plus?

Every class requires at least one constructor, the copy constructor. It is implied if not declared. If no constructors are declared, a default constructor is also implied. Every class also requires a destructor, which is also implied if not declared. The purpose of constructors is to construct the object (obviously) but by defining your own you can control how the object is constructed, and how member variables are initialised. By overloading constructors, you allow instances of your object to be constructed in several different ways. The copy constructor's default implementation performs a member-wise copy (a shallow-copy) of all the class members. If your class includes pointers, you will invariably need to provide your own copy constructor to ensure that memory is deep-copied. That is, you'll want to copy the memory being pointed at, not the pointers themselves (otherwise all copies end up pointing to the same memory, which could spell disaster when one of those instances is destroyed). The destructor allows you to tear-down your class in a controlled manner, including cleaning up any memory allocated to it. If your class includes pointers to allocated memory, you must remember to delete those pointers during destruction. The destructor is your last-chance to do so before the memory "leaks". The implied destructor will not do this for you -- you must implement one yourself. class foo { public: foo(){} // Default constructor. foo(const foo & f){} // Copy constructor. ~foo(){} // Destructor. };

Related questions

Constructor cannot be virtual but destructor can be virtual justify?

bcoz constructor cant be invoked


Constructor and destructor invocation in c?

Not possible in C.


What is difference between constructor and destructor in net?

dono lah bodo


Why pointer of constructor is made but not of destructor?

When a constructor is invoked dynamically, the new operator allocates the required memory, initialises it according to the constructor, then returns a pointer to the allocation. The destructor is invoked by deleting the pointer. It wouldn't make any sense to return a pointer from a deletion.


How can you recognize a constructor in a class?

A class's constructor will have the same name of the class and no return type (not even void): class Example(){ Example() {printf("This is the constructor\n");} ~Example(){printf("This is the destructor\n");} };


What is the difference between the constructor to and destructor?

Functions and Constructors are similar in many ways. They can have arguments, they can have any amount of code, they can access the class's variables etc. the only difference is that a method in java needs to mandatorily have a return type but a Constructor in java cannot have a return type. It always creates and returns an object of the class for which it is the constructor. You cannot return a value from a constructor explicitly and if you try to do that, the compiler will give an error. The system knows that the purpose of the constructor is to create an object of the class and it will do the same irrespective of whether you declare a return type or not.


A method that is automatically called when an instance of a class is created?

The constructor of a class is automatically called when an instance of the class is created (using new in C++). The constructor method has the same name as the class that it is a part of. Constructors have no type and do not return anything. Similarly, the destructor is automatically called when the instance of the class is destroyed. The destructor is the same name as the class and is preceded by a tilde (~) For example: class Example { public: Example() // Constructor { printf("Object created\n"); } ~Example() // Destructor { printf("Object destroyed\n") } }; int main() { Example* x = new Example(); // Creates object, calls constructor delete x; // Calls destructor, deletes object return 0; }


Which class methods does the compiler generate automatically if you don't provide them explicitly?

Default constructor: X()Copy constructor: X(const X&)Copy assignment operator: X& operator=(const X&)Move constructor: X(X&&)Move assignment operator: X& operator=(XX&)Destructor: ~X()By default, the compiler will generate each of these operations if a program uses it. However, if the programmer declares any constructor for a class, the default constructor for that class is not generated. If the programmer declares a copy or move operation, no copy, move or destructor is generated. If the programmer declares a destructor, no move operation is generated (a copy constructor is generated for backward compatibility).We can also suppress generation of specific operations with the =delete pseudo-initialiser:class X {public:X (const X&) =delete; // suppress the compiler-generated copy operationsX& operator=(const X&) =delete;// ...};


Why constructor and destructor cannot be made static?

The term "destructor" made me believe this question is related to .Net languages. A destructor is to destroy an instance of object. If it is available at static/class level, what is it going to destroy? The entire class, so the class no longer available? Thus, semantically, destructor should be an instance method. Constructor is on the opposite end of the life cycle of an instance. However, in .NET, a static constructor is allowed. Personally, I call this static constructor as a class initialization method. This method will be invoked by the .net framework only once when the class is loaded into the application domain. With the similar concept, there should be a "finalizer" of the class when the class is unloaded out of the application domain. But wait, does a class ever go out of the application domain once it's loaded? Yes, only at the termination of the application! Currently a class cannot be unloaded explicitly in codes and thus no point to have a static finalizer.


How do you construct a program with destructor more than constructors?

The question is unclear, but classes can only have one destructor at most. They can have as many constructors as required. Even if you do not declare any constructors, the compiler will automatically generate a default constructor (which initialises all member variables to zero) and a copy constructor (which performs a member-wise, shallow copy of the members). If your class contains member pointers and allocates memory to them, you must provide your own destructor to clean up those memory allocations as well as provide a copy constructor to deep copy the memory allocations (thus ensuring no two instances of the class point to the same memory).


Parameterized constructor in c plus plus?

Every class requires at least one constructor, the copy constructor. It is implied if not declared. If no constructors are declared, a default constructor is also implied. Every class also requires a destructor, which is also implied if not declared. The purpose of constructors is to construct the object (obviously) but by defining your own you can control how the object is constructed, and how member variables are initialised. By overloading constructors, you allow instances of your object to be constructed in several different ways. The copy constructor's default implementation performs a member-wise copy (a shallow-copy) of all the class members. If your class includes pointers, you will invariably need to provide your own copy constructor to ensure that memory is deep-copied. That is, you'll want to copy the memory being pointed at, not the pointers themselves (otherwise all copies end up pointing to the same memory, which could spell disaster when one of those instances is destroyed). The destructor allows you to tear-down your class in a controlled manner, including cleaning up any memory allocated to it. If your class includes pointers to allocated memory, you must remember to delete those pointers during destruction. The destructor is your last-chance to do so before the memory "leaks". The implied destructor will not do this for you -- you must implement one yourself. class foo { public: foo(){} // Default constructor. foo(const foo & f){} // Copy constructor. ~foo(){} // Destructor. };


1 Explain the concepts of constructor and destructor Do you have to declare a constructor every time you create a class?

You only need a constructor if the default constructor will not suffice. Often times, it is useful to have a constructor that takes common parameters so that you do not have to write additional code. For example, a Point class might have a constructor for Point(int x, int y), which would be a shortcut for assigning x and y independently. Other classes may not need any default values assigned, and for this, it is acceptable to just use the default constructor. Finally, some classes are virtual, static, or abstract, and so may not need a constructor because the constructor is unnecessary (static), or may be defined elsewhere (virtual, abstract).