answersLogoWhite

0


Best Answer

Yes, you can use, and often you should, use more than one constructor in a class in C++.

Normally, there is a default constructor, a copy constructor, and one or more conversion constructors. Sometimes, there are also other constructors, overloaded based on argument signature, if there are complex situations.

User Avatar

Wiki User

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

Wiki User

9y ago

C++ has three basic constructors: a default constructor (one with no arguments or where all arguments have default values), a copy constructor and a move constructor. You can also define your own constructors, so long as each has a unique signature.

If you do not define any constructors, the three basic constructors are generated for you by the compiler. If you define any constructor, you lose the compiler-generated default constructor unless you define your own.

The compiler-generated constructors perform member-wise initialisation. In most cases this is fine, particularly if you use Resource Acquisition Is Initialisation (RAII) techniques (e.g., smart pointers). However, if you need to establish class invariants, you must define your own constructor(s) to cater for them. Copy and move constructors will still be generated by the compiler and if using RAII will be sufficient. The only real reason to declare your own copy or move constructors is in cases where you wish to physically disable them.

The compiler also generates copy and move operators as well as a destructor. Most class designers like to be explicit with their construction, assignment and destruction however the latest standard (C++11) permits designers to simplify their declarations to explicitly use compiler-generated defaults:

class A

{

public:

~A () = default;

A () = default;

A (const A&) = default; // copy

A& operator= (const A&) = default;

A (A&&) = default; // move

A& operator= (A&&) = default;

// user-defined members...

};

To delete any compiler-generated method, use =delete in place of =default. This will result in a compile-time error if those methods are called and is much better than previous techniques that involved using private methods without function bodies.

This answer is:
User Avatar

User Avatar

Wiki User

9y ago

There are three basic constructors: the default constructor (one that accepts no arguments or where all the arguments have default values); the copy constructor and the move constructor. But you can also have any number of overloaded constructors over and above these three. There are no limits to the number of constructors you can define, other than those imposed by the architecture (e.g., memory restrictions).

This answer is:
User Avatar

User Avatar

Wiki User

12y ago

All constructors have two things in common: they all create a new instance of an object, and they do not specify a return type (a reference to the class is implied, or a pointer to the class if it is created with the new keyword).

The purpose of the constructor is to allow the class developer to initialise the class member variables to default values, or to values specified by the caller. Constructors may also invoke internal methods or external functions to further initialise the class.

Constructors may be public, protected, or private, as required by the class. Typically, there will be at least one public or protected constructor. If all constructors are declared private, no instance of the class can be created (useful for classes that have no member variables and all member methods are declared static).

The default constructor is implied (with public access) when not explicitly declared. A default constructor takes no arguments, however you may include arguments in your override provided all the arguments are given default values. If your class includes member variables you will typically override the default constructor to ensure those variables are initialised correctly. Derived classes will automatically invoke their base class default constructor(s) which should be declared protected or public. Private default constructors are also permitted provided the derived classes are also declared friends of the base class (this feature should only be considered when you do not expect to derive additional classes from the base class).

The copy constructor accepts one argument; a constant reference to another instance of the same class. The default implementation will perform a member-wise copy of the argument (a shallow-copy). Sometimes this is sufficient and there is no need to override the copy constructor. However, if your class contains a pointer to allocated memory, the copy will end up pointing at that same memory location. Sometimes this may be desirable (if the memory were allocated outside of the class, for instance) but if the memory is allocated within the class then the assumption is it will also be released by the instance that allocated it. That is a recipe for disaster when two instances point at the same memory; which instance actually owns the memory, and what happens when either instance is destroyed? The safest solution is to perform a deep-copy of the memory so both instances point to different memory locations, in which case the copy constructor must be overridden. If you do not wish copies of your class to be made, declare the copy constructor private.

Additional construction overloads can be provided by the developer to increase the flexibility with which a user can create instances of the class. For example, if your class has a double member variable, you might allow users to initialise the class member by passing a double into a constructor overload. You might also consider allowing the class to be initialised by passing an integer, or some other numeric type, so the class can handle the type-casting internally, rather than expecting the user to do it. Other uses for constructor overloading include the ability to instantiate your class from an instance of another class entirely, essentially allowing you to "morph" one class type into an entirely different class type, which may include base classes and derived classes. This is a powerful feature, but should only be used where it makes sense to do so. If the end result is an invalid object, then it makes no sense to allow the object to be constructed in the first place.

If your class has multiple members, it can often be useful to create a structure from those members, and to provide a constructor to accept the structure as an argument, thus giving users of your class additional flexibility in creating instances of your class.

The assignment operator is not a constructor (it assigns values to an existing instance of a class, it does not create a new instance), however it is considered good practice to include an assignment operator overload for every constructor overload except the default constructor and those that accept multiple arguments (you can only assign one value with assignment, but structures and classes can be used wherever it is deemed appropriate). This will greatly increase the flexibility of your class. As a general rule, the more flexible your class is, the more your users, and particularly yourself, are likely to use it, which is surely the whole point of creating the class in the first place.

This answer is:
User Avatar

User Avatar

Wiki User

13y ago

Default, Copy, Conversion, Implied (a case of default).

This answer is:
User Avatar

Add your answer:

Earn +20 pts
Q: Can you use more than one constructor in a class in c plus plus?
Write your answer...
Submit
Still have questions?
magnify glass
imp
Continue Learning about Engineering

How do you invoke the constructor function in c plus plus?

There is no such thing as a constructor function in C++ (constructors have no return value, not even void, and cannot be called like regular functions). Constructors are invoked rather than called directly, either by declaring a static variable of the class type, or via the C++ new operator.


What is the use of private constructor in c plus plus?

Private construction prevents objects from the class from being instantiated other than via a static member function of the class, a friend function or a friend class.


What is the method of constructor overloading in c plus plus?

Constructor overloading, just like any function's overloading, is where more than one configuration of parameters exists for the function. Based on the number and type of the parameters, different versions of the function can be resolved by the linker. This is typically used in the constructor as the default constructor (no parameters), the copy constructor (one reference parameter of the same type as the class), and the conversion constructor (any other combination of parameters).


What are the properties of class in c plus plus?

A constructor is not a function. A function is a type, as specified by its return type, and must return a value of that type unless the type is void. A constructor does not return anything, not even void. The purpose of a constructor is to both allocate and initialise memory for an object of the type being constructed. If a valid object cannot be constructed for any reason, the constructor must throw an exception. If the object's class has no data members (attributes), the class does not require a constructor. This is typically the case for most abstract data types and base classes which are used purely as interfaces. Constructors differ from functions in that all constructors have an initialisation section that is used specifically to initialise non-static data members. The body of the constructor is rarely used except to perform initialisations that cannot be more easily performed by the initialisation section. A class may have more than one constructor to provide alternative methods of construction based upon the number and type of arguments supplied (if any). When no arguments are required or all arguments have default values then the constructor is known as the default constructor. If the constructor has only one argument the constructor is known as a conversion constructor (because the argument is converted to an object of the class). However, if the constructor argument is a constant reference to an object of the same class, then it is known as a copy constructor, and when the constructor argument is an rvalue reference, it is known as a move constructor. If copy and/or move constructors are provided for a class, the equivalent assignment operators should also be provided for that class. All other constructors are known as user-defined constructors.


Can you have more than 1 constructor in a class?

Yes. At least in Java, that's possible, as long as the constructors have a different number, or different types of, parameters.

Related questions

How do you invoke the constructor function in c plus plus?

There is no such thing as a constructor function in C++ (constructors have no return value, not even void, and cannot be called like regular functions). Constructors are invoked rather than called directly, either by declaring a static variable of the class type, or via the C++ new operator.


What is the use of private constructor in c plus plus?

Private construction prevents objects from the class from being instantiated other than via a static member function of the class, a friend function or a friend class.


What is the method of constructor overloading in c plus plus?

Constructor overloading, just like any function's overloading, is where more than one configuration of parameters exists for the function. Based on the number and type of the parameters, different versions of the function can be resolved by the linker. This is typically used in the constructor as the default constructor (no parameters), the copy constructor (one reference parameter of the same type as the class), and the conversion constructor (any other combination of parameters).


What are the properties of class in c plus plus?

A constructor is not a function. A function is a type, as specified by its return type, and must return a value of that type unless the type is void. A constructor does not return anything, not even void. The purpose of a constructor is to both allocate and initialise memory for an object of the type being constructed. If a valid object cannot be constructed for any reason, the constructor must throw an exception. If the object's class has no data members (attributes), the class does not require a constructor. This is typically the case for most abstract data types and base classes which are used purely as interfaces. Constructors differ from functions in that all constructors have an initialisation section that is used specifically to initialise non-static data members. The body of the constructor is rarely used except to perform initialisations that cannot be more easily performed by the initialisation section. A class may have more than one constructor to provide alternative methods of construction based upon the number and type of arguments supplied (if any). When no arguments are required or all arguments have default values then the constructor is known as the default constructor. If the constructor has only one argument the constructor is known as a conversion constructor (because the argument is converted to an object of the class). However, if the constructor argument is a constant reference to an object of the same class, then it is known as a copy constructor, and when the constructor argument is an rvalue reference, it is known as a move constructor. If copy and/or move constructors are provided for a class, the equivalent assignment operators should also be provided for that class. All other constructors are known as user-defined constructors.


Why constructor rather than classes in java?

Constructor is not an alternative to class. In Java, you create classes; the classes contain methods - including the constructor, which can be viewed as a special method. If you want to have a constructor, you need a class that surrounds it, so it's not one or the other.


What is constructor and discuss different types of constructor with syntax and examples?

A constructor is a class method which initialises an object of the class at the point of instantiation. Specifically, it initialises the base classes (if any) and the non-static data members (if any). Constructors also play a central role in the resource acquisition is initialisation (RAII) paradigm. Objects which have a natural default value have a default constructor. The default constructor is a constructor that has no arguments or where all arguments have default values. Objects which can be copied have a copy constructor. The copy constructor has just one non-default argument, a const l-value reference of the same type as the class. Objects which can be moved have a move constructor. The move constructor has just one non-default argument, a modifiable r-value reference of the same type as the class. All other constructors that have only one argument of a type other than the class itself are known as conversion constructors. Constructors can also have more than one argument. No specific name is given to these constructors. Other than physical memory constraints, there is no limit to the number of constructors that may be defined for a class.


What is an array of class objects.how the array of class of class objects is defined in c plus plus?

An array of class objects is just a set of class objects arranged linearly in memory. It is no different than an array of elementary objects. You define it the same way. class myClass { ... }; myClass arrayOfMyClass[100]; // creates 100 objects and fires the constructor 100 times


How do you declare constructor in cpp?

More or less as you would any other function, except there is no return type (not even void) and an initialisation list can be placed between the declaration and the definition that follows it. The initialisation list allows your constructor to call base class constructors besides the default constructor as well as initialise member variables according to the parameters passed to your constructor. The constructor's name must be the name of the class. Note that if you don't declare any constructors, the compiler generates both a default and copy constructor. If any constructor is declared you lose the default constructor unless you declare one yourself. The copy constructor is always present but must be overridden if your class contains pointers to memory allocated to the class itself. If you don't, the compiler generated copy constructor will perform a member-wise copy of the member variables, resulting in a shallow copy of the pointers themselves, rather than a deep copy of the memory they point to. The copy constructor must accept a constant reference to the same class of object.


Can you have more than 1 constructor in a class?

Yes. At least in Java, that's possible, as long as the constructors have a different number, or different types of, parameters.


Can you overload the constructor in java true or false?

Yes, you can have more than one constructor with a different set of parameters.


How do you call multiple constructors with single object?

You can have any number of constructors for a class. All we need to do is implement constructor overloading. Ex: let us say we want to create multiple constructor for a class Test Public class Test { Public Test() { //code } Public Test(int vals) { //code } Public Test(String val) { //code } }


When is parameterized constructor required in c?

A parametrised constructor is any constructor that accepts one or more arguments where the first argument has no default value. If all parameters have default values then the constructor is regarded as being a default constructor that is overloaded. The copy constructor is an example of a parametrised constructor. If you do not define your own, one is generated for you by the compiler, However, the compiler-generated copy constructor performs a member-wise copy. If your class contains member pointers to memory allocations that are owned by the class, this will result in two or more classes owning the same memory, which would prove disastrous when any one instance is destroyed (it will completely invalidate all other instances). Therefore you must provide your own copy constructor to ensure every instance of the class owns its own allocations, by deep copying the pointers (copying the memory being pointed at rather than just the pointers). Other than that, there is no requirement to provide any parametrised constructor. You only need to provide parametrised constructors when you want to provide an alternative method of construction. Note that if you declare any parametrised constructor, including a copy constructor, the compiler does not generate a default constructor for you. If you require one, then you must provide your own. The default constructor may be parametrised provided all parameters are assigned default values. As an example, consider the following simple class that has a default constructor (as well as a compiler-generated copy constructor): class simple { public: simple():m_data(0){} void setdata(const float data){m_data = data;} void setdata(const int data){m_data = ( float ) data;} private: float m_data; }; When we instantiate this class, the data member is initialised to 0. If we wish to change the data member, we must subsequently call one of the setdata() methods. However, it would be more efficient to set the data member when the class is instantiated. Therefore we should provide a parametrised default constructor: simple(float data=0):m_data(data){} We should also provide a parametrised constructor to cater for integers: simple(int data):m_data(( float ) data){} Now we no longer need to call setdata() to initialise the class as we can do it all via the constructors.