How to overload assign operator for assigning a object at the time of initialization in c++

Viewed 88

i want to overload the assignment operator such that it will be used to assign data at the time of initialization of object

for initializing a string object we can follow the format given below

string str = "Hello World !!!";

but it will be a error if we define our object in same manner;

for example

#include<iostream>
using namespace std;
class Name{
private:
    string name;
public:
    Name(){}
    Name(string str){
        name=str;
    }
};
int main(){
    Name name="Jack";
}

it is showing error like

E:\Documents\test.cpp||In function 'int main()':|
E:\Documents\test.cpp|13|error: conversion from 'const char [5]' to non-scalar type 'Name' requested|
||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

so how to make a class such that it can accept data like string object .

2 Answers

Firstly, Name name="Jack"; is initialization, not assignment, so it has nothing to do with assignment operator.

Note that "Jack" is not a std::string, but a string literal with type const char[5]. Then for Name name="Jack";, which is copy initialization, it needs to be converted to std::string and then converted to Name. But only one user-defined conversion is allowed in one conversion sequence.

You can add another constructor taking const char*,

class Name{
    ...
    Name(const char* s) : name(s) {}
};

Implicit conversion from const char[] to const char* is qualified as standard conversion then the code works fine.

Or change Name name="Jack"; to Name name("Jack");, which is direct initialization, "Jack" will be converted to std::string, and the constructor of Name taking std::string will be invoked directly to initialize the object.

Or use Name name = "Jack"s;, while "Jack"s is a std::string literal (since C++14) with type std::string, then only one conversion (from std::string to Name) is needed.

The right hand side of this line (which is not an assignment but an object definition and an initialization):

Name name = "Jack";

invokes the fifth string constructor overload because "Jack" is a string literal of type const char[] and not std::string which is what your user defined Name(string str) constructor expects. To make it of type std::string append the s literal using the operator ""s which constructs a literal of type std::string:

Name name = "Jack"s;

and compile with C++14 support enabled or add a constructor that accepts const char* parameter:

Name(const char* str) { 
    name = str;
}

Either way you need to include the <string> header when working with std::string type.

Related