Home > other >  having trouble with constructors that take default arguments
having trouble with constructors that take default arguments

Time:01-04

I am quite new to this level of coding. Here is the offending code

#include <iostream>

class var {
public:
    var(const var& v, char name = ' ') : name_(name) {}
          
    explicit var(double v, char name = ' ') : name_(name) {}
        
    char name() { return name_; }
    
private:
    char name_; 
};  

int main() {
    var x(10, 'x');
    var y = x;
    std::cout << x.name() << std::endl; // 'x'
    std::cout << y.name() << std::endl; // ' '
    return 0;
}   

when I inspect the objects being generated the value of x is 'x', and the value of y is ' '. This should also be 'x'

CodePudding user response:

You have redefined a copy constructor therefore var y = x; calls var(const var& v, char name = ' ') and not the default, "expected" one.

This sets name_ to ' ', so it should not be 'x'.

I would recommend to refactor var to something like:

class var {
public:

    var(char name=' ') : name_(name) {}
    var(const var& v) =default;
    explicit var(double v, char name = ' ') : name_(name) {}
     
    //...
private:
    char name_; 
};  
  •  Tags:  
  • c
  • Related