0

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'

HMPtwo
  • 139
  • 4
  • 3
    Please provide a [Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example). For example, if you think that the problem lies in the constructor, scrap all routines in the class except the constructors, and provide a simple test program that tests your problems. – francesco Jan 02 '23 at 19:39
  • Not explicit constructor `var(const var& v, char name= ' ')` will be chosen as a copy-constructor but it doesn't copy `name_`. – 273K Jan 02 '23 at 19:49
  • What do you mean it does not copy name? – HMPtwo Jan 02 '23 at 19:54
  • I have added a minimal reproducible example. – HMPtwo Jan 02 '23 at 20:02
  • `name_(name)` it doesn't copy `v.name_` – 273K Jan 02 '23 at 20:36

1 Answers1

1

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_; 
};  
Quimby
  • 17,735
  • 4
  • 35
  • 55
  • What is the nicest way to deal with this? I am learning as I go along. – HMPtwo Jan 02 '23 at 20:05
  • 1
    @HMPtwo simply remove the default argument. The generated copy-constructor will work fine, and yours will kick in if the user provides an override for the name. – Quentin Jan 02 '23 at 20:06
  • @HMPtwo Do not write `var(const var& v, char name = ' ')` - split the "copy" from "initializaton" - I have edited my answer. – Quimby Jan 02 '23 at 20:08
  • *I am learning as I go along.* You'd be much better off by learning with a [good C++ book](https://stackoverflow.com/a/388282/4641116). C++ is a very big & old language (still evolving, but with many backwards compatibility concessions), with lots of interesting behavior, and plenty of opportunity to be lulled into a false sense of confidence because it is very easy to code **undefined behavior**. – Eljay Jan 02 '23 at 22:09