answersLogoWhite

0


Best Answer

You have to explicitly initialise all instance variables, otherwise their values will be initialised to whatever happens to be in memory at the time they are instantiated.

Consider the following class which has no explicit initialisation:

#include <iostream>

class object

{

public:

object(){}

public:

const int getData( void ) const { return( m_data ); }

private:

int m_data;

};

int main()

{

object O;

printf( "O.m_data = %d\n", O.getData() );

return( 0 );

}

Example output:

O.m_data = -858993460

This is not particularly useful; we must ensure m_data is initialised before we access its value.

One way to initialise object::m_data is from within the body of the constructor:

object(){ m_data = 0; } // inefficient initialisation

However this is quite inefficient because object::m_data will have already be instantiated by the time we got to the constructor body. This is akin to the following C-style initialisation:

int x; // instantiate x

x = 0; // initialise x

When what we really want to do is:

int x = 0;

Or use the more formal construction semantics:

int x(0);

Both achieve the same thing. They both initialise the variable x at the point of instantiation, not after instantiation. Fortunately, C++ allows us to initialise all instance variables at the point of instantiation, via the constructor's initialisation section:

object():m_data(0){} // efficient initialisation

While initialising a single primitive data type in the constructor body isn't going to cause major problems in terms of efficiency, with more complex data types the inefficiencies can very quickly add up. Thus it is important to use the initialisation section as much as possible and to only use the body of the constructor when there is no option.

The initialisation section is particularly important when dealing with derived classes. Consider the following:

#include <iostream>

class base

{

public:

base():m_int(0){}

base(const base& object):m_int(object.m_int){}

public:

const int getInt( void ) const { return( m_int ); }

void setInt( const int data ) { m_int = data; }

private:

int m_int;

};

class derived : public base

{

public:

derived():m_float(0.0){}

derived(const derived& object):m_float(object.m_float){}

public:

const float getFloat( void ) const { return( m_float ); }

void setFloat( const float data ) { m_float = data; }

private:

float m_float;

};

int main()

{

derived d;

d.setInt( 1 );

d.setFloat( 2.0 );

printf( "d.getInt() = %d, d.getFloat() = %f\n", d.getInt(), d.getFloat() );

derived c(d); // call copy constructor.

printf( "c.getInt() = %d, c.getFloat() = %f\n", c.getInt(), c.getFloat() );

return( 0 );

}

Example output:

d.getInt() = 1, d.getFloat() = 2.000000

c.getInt() = 0, c.getFloat() = 2.000000

Note that c should be an exact copy of d, but there's clearly a difference in the integer variables inherited from the base class. This is because the derived class copy constructor called the base class default constructor, not the base class copy constructor as you might have expected. To resolve this we must explicitly call the base class copy constructor and the only way to do so is via the initialisation section of the derived class:

derived(const derived& object):base(object),m_float(object.m_float){}

Note that the derived class' copy constructor now includes a call to base(object) in the initialisation section. This ensures the base class copy constructor is called. Although object is actually an instance of derived, because it derived from base it is also a kind of base, thus the call is legitimate. Now if we run the code we'll get the expected result:

d.getInt() = 1, d.getFloat() = 2.000000

c.getInt() = 1, c.getFloat() = 2.000000

As your classes become more and more complex you will inevitably find yourself creating overloaded constructors to provide a wide variety of initialisation methods. But keep in mind that it costs absolutely nothing to use the initialisation sections even if several constructors end up using the exact same initialisations. And while it is tempting to move all of the common initialisation code into a private method of the class and have each constructor call that method (known as a construction helper function), this simply adds yet more inefficiency by introducing yet another unnecessary function call. Helper functions such as these are undoubtedly useful during the initial development of a class but as soon as the class is finalised, get rid of the helper function and move all that functionality into the initialisation sections where they belong. In the case of derived classes, base class constructors will be called whether you like it or not, so it makes sense to call the most appropriate base class constructor from within the initialisation section of each of your derived class constructors. Remember that if you do not specify a base class constructor, its default constructor will be called implicitly, which may or may not be the most appropriate constructor in all cases (not least in the case of the copy constructor).

User Avatar

Wiki User

11y ago
This answer is:
User Avatar

Add your answer:

Earn +20 pts
Q: How are an objects instance variables initialized of a class has only a default constructor?
Write your answer...
Submit
Still have questions?
magnify glass
imp
Continue Learning about Engineering

What is the default initial value for all numeric types?

If they are instance variables the default initial value is 0. If they are method local variables, they are null and must be initialized to some value before they are used


Are C variables initialized to 0 by default?

Only global/static variables are, local variables aren't.


Why Java always provides a default constructor to class when you use another constructor default constructor remove?

Classes in Java inherit constructors from their parent classes. If you don't explicitly define a parent class, then Object is used, which has only the default empty constructor. That "default" constructor is only there when defined by the parent class, so classes which do not have a no-argument constructor will not allow subclasses to automatically use it. This is implemented this way because of the special nature of constructors. Java could not always provide a default constructor because it could not guarantee that all class members would be properly created or initialized.


How do you get a default constructor?

The default constructor is an empty (only call the super constructor) with no parameters constructor inserted by the java compiler when you don't define a constructor in your class. If you write something like this: public class NoConstructorClass{ //no constructor goes here } Then you get something like this: public class NoConstructorClass{ public NoConstructorClass(){ // Default constructor that you didn't write super(); } }


What happens if you don't initialize an instance variable of any of the primitive type in java?

Java by default initializes it to the default value for that primitive type. Thus an int will be initialized to 0(zero), a Boolean will be initialized to false.

Related questions

What is the default initial value for all numeric types?

If they are instance variables the default initial value is 0. If they are method local variables, they are null and must be initialized to some value before they are used


Are C variables initialized to 0 by default?

Only global/static variables are, local variables aren't.


Why Java always provides a default constructor to class when you use another constructor default constructor remove?

Classes in Java inherit constructors from their parent classes. If you don't explicitly define a parent class, then Object is used, which has only the default empty constructor. That "default" constructor is only there when defined by the parent class, so classes which do not have a no-argument constructor will not allow subclasses to automatically use it. This is implemented this way because of the special nature of constructors. Java could not always provide a default constructor because it could not guarantee that all class members would be properly created or initialized.


How do you get a default constructor?

The default constructor is an empty (only call the super constructor) with no parameters constructor inserted by the java compiler when you don't define a constructor in your class. If you write something like this: public class NoConstructorClass{ //no constructor goes here } Then you get something like this: public class NoConstructorClass{ public NoConstructorClass(){ // Default constructor that you didn't write super(); } }


What happens if you don't initialize an instance variable of any of the primitive type in java?

Java by default initializes it to the default value for that primitive type. Thus an int will be initialized to 0(zero), a Boolean will be initialized to false.


Default constructor in java?

If you don't type a constructor into your class code, a default constructor will be automatically generated by the compiler. The default constructor is ALWAYS a no-arg constructor. (Obviously the compiler has no clue what all arguments you might want for your class. So it takes the safe way out with a no argument constructor) A no-arg constructor is not necessarily the default (i.e., compiler-supplied) constructor, although the default constructor is always a no-arg constructor. The default constructor is the one the compiler provides! While the default constructor is always a no-arg constructor, you're free to put in your own no-arg constructor.


What is a default parameterized constructor?

There is no such thing as a default parameterized constructor. The default constructor is always the 'no-arg' constructor and does not take any parameters or arguments as input


How is the default constructor equivalent to a constructor having default arguments?

Any constructor that can be invoked without explicitly passing any arguments is a default constructor. Note that there can be only one default constructor so there can only be one constructor where all arguments have default values or one constructor that has no arguments, but not both. A constructor where all arguments have default values is a useful means of combining two or more constructors into a single default constructor, thus reducing verbosity and code duplication.


When a object is passed to a function as argument why it is not generating an error if the parameterized constructor is defined and not the default constructor?

default constructor is used only when the programmer does not use a constructor to initialize objects. Once the programmer defines a constructor then the default constructor is no longer used


Why you use constructor chaining?

Constructor ChainingWe know that constructors are invoked at runtime when you say new on some class type as follows:Lamborghini h = new Lamborghini();But what really happens when you say new Lamborghini() ? (Assume Lamborghini extends Car and Car extends Object.)1. Lamborghini constructor is invoked. Every constructor invokes the constructor of its superclass with an (implicit) call to super(),2. Car constructor is invoked (Car is the superclass of Lamborghini).3. Object constructor is invoked (Object is the ultimate superclass of all classes, so class Car extends Object even though you don't actually type "extends Object" into the Car class declaration. It's implicit.) At this point we're on the top of the hierarchy.4. Object instance variables are given their explicit values. By explicit values, we mean values that are assigned at the time the variables are declared, like "int x = 27", where "27" is the explicit value (as opposed to the default value) of the instance variable.5. Object constructor completes.6. Car instance variables are given their explicit values (if any).7. Car constructor completes.8. Lamborghini instance variables are given their explicit values (if any).9. Lamborghini constructor completes.


Can you declare default constructor as private?

Yes, but that means you can't define an instance of the class without arguments to new.


What is another name of default constructor?

No-Arg Constructor