1

I am trying to create objects of Contact. But I am not able to do that with initializer list. When I remove new inside Contact class constructor, it works fine but when I add new, compiler throws an error. I want to understand why I am not able to use initializer list. Where can I use initializer list and where can I not?

#include"stdafx.h"
#include<string>
using namespace std;

struct Address
{
    string street;
    string city;
};

struct Contact
{
    string name;
    Address* address;
    Contact(const Contact& other)
        : name{other.name},
          address( new Address(*other.address) ) {}
    ~Contact()
    {
        //delete work_address;
    }
};

int main()
{
    auto address = new Address{ "123 East Dr", "London" };                        
    //Issue while creating john and jane below 
    //Compiler error: Cannot initialize john with initializer list
    Contact john{ "John Doe", address };                                          
    Contact jane{ "Jane Doe", address };
    delete address;
    getchar();
    return;
}
Sam
  • 55
  • 3

1 Answers1

0

Contact class constructor, it works fine but when I add new, compiler throws an error.

You most likely mean "after I added the copy constructor, compiler throws an error".

Using

Contact(const Contact& other)
    : name{other.name},
      address( Address(*other.address) ) {} // Without the new

is obviously wrong. You cannot initialize a pointer with an object.

You can use:

Contact john{"John Doe", address};                                          

only if:

  1. There is an appropriate constructor given the arguments, or
  2. There is no user defined constructor.

Since neither of those is true after you add the copy constructor, the compiler correctly points that out as an error.

You can fix that by adding another user defined constructor:

Contact(string const& n, Address* a) : name(n), address(a) {}

N.B.

Please note that you need to follow The Rule of Three for you class. Otherwise, you will run into problems at run time.


N.B. 2

In main, you have

return;

That is not correct. You should remove that line or change it to

return 0;
R Sahu
  • 204,454
  • 14
  • 159
  • 270