pw94
pw94

Reputation: 401

Copy constructor should copy *string values

I have a class:

class BankAccount
{
    string *name;
    string *number;
public:
    BankAccount(BankAccount &);
    ~BankAccount();
};

BankAccount::BankAccount(BankAccount &account)
{
    string nameS = account.name;
    this->name = new string(nameS);
    this->number = new string(account.*number);
}

I would like to that my copy constructor copy the strings (not the pointers, but strings pointed by pointers) to new object. I tried two different methods but I've never succeeded.

Compiler messages:

conversion from 'std::string* {aka std::basic_string<char>*}' to non-scalar type 'std::string {aka std::basic_string<char>}' requested

'((BankAccount*)this)->BankAccount::number' cannot be used as a member pointer, since it is of type 'std::string* {aka std::basic_string<char>*}'

Upvotes: 0

Views: 1418

Answers (2)

HarryRose
HarryRose

Reputation: 66

The class BankAccount should probably just contain string objects rather then pointers to strings

class BankAccount
{
    string name;
    string number;
};

Edit: as pointed out by other users, you now no longer need to write a copy constructor or destructor as std strings take care of themselves

Upvotes: 2

harmic
harmic

Reputation: 30577

As per the other comments and answers, in this case there is no need to use pointers as instance variables. You would be better off just making the instance variables actual strings. But just to explain your problem:

string nameS = account.name;

account.name is a pointer to a string, so you need this:

string nameS = *account.name;

In this statement:

this->number = new string(account.*number);

You are dereferencing incorrectly. It should be:

this->number = new string(*account.number);

Upvotes: 2

Related Questions