简体   繁体   中英

c++ constructor with default argument

Hello I made this class that has a default constructor and a constructor with default argument

Something.h

class Something  // Fraction class
{
public:
      Something (void); // default ctor
      Something (int xx, int yy = 1 );
          int x,y; 
}         

Something.cpp

Something::Something(){}

Something::Something(int xx, int yy)
{
    x = xx;
    y = yy;
} 

but when I make object with no parameter and print it, it will show that x = 0, y = 0;

where might be the problem :( Thanks!

When you make an object with no arguments, you call the default constructor:

Something::Something(){}

This one does not initialize x or y , which means you could get any value that fits in an int . Presumably you are using a debug configuration, so you get x and y initialized to 0 . Whatever the reason, you should not count on that behaviour.

To invoke the constructor with the default argument, you need to call it with one or two arguments:

Something s1(5);
Something s2(5,6);

Edit if you want to make sure your default constructor zero-initializes x and y , you can do so explicitly in the initialization list:

Something::Something() : x(0), y(0) {}

If you call with no parameters, you will be calling this constructor

Something::Something(){} 

instead of this

Something::Something(int xx, int yy) 

so your initialisation code wont get called as you have provided none explicitly and you will get a default value upon initialisation of your integer members - in this case it was zero, but it could be any integer value. For this reason it is good practice to initialise your member variables in the constructor implementation. For example implementing it like this

Something::Something() : x(1),y(1) {} 

will result in x and y being set to 1 when you create an instance of your object with the zero argument constructor.

The reason for this problem is that you have written the overloaded constructor for this and but you calling the constructor with no parameters so the by default the default constructor is being called and no assignment happens to your variables.

You have to pass the arguments for inorder to invoke the overloaded constructor. You overloaded constructor have assigned default value of 1 to yy so if you just simply pass one argument xx will be assigned that value and yy will have the default value of 1 in this case. But if you will pass the two arguments the xx and yy will be assigned those values respectively.

when I make object with no parameter and print it, it will show that x = 0, y = 0;

By default, the instance fields are initialized to their default value. For int data-type the default value is 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM