Programmer
Programmer

Reputation: 8687

C++ unable to create instance of an class

I am not able to understand why the object creation n my below code is wrongly implemented:

#include <iostream>
#include <string>
class A
{
public:
    A(std::string apptype) : m_apptype(apptype)
    {
        std::cout << m_apptype << std::endl;
    }
    A(std::string&& apptype) : m_apptype(apptype)
    {
        std::cout << m_apptype << std::endl;
    }
private:
    std::string m_apptype;
};

int main()
{
    A(std::string("Test"));
    return 0;
}

I get the below error when I compile my code:

$ c++ Calender.cpp
Calender.cpp:10:14: error: expected ',' or '...' before '&&' token
 A(std::string&& apptype) : m_apptype(apptype)
              ^
Calender.cpp:10:1: error: 'A::A(std::string)' cannot be overloaded
 A(std::string&& apptype) : m_apptype(apptype)
 ^
Calender.cpp:6:1: error: with 'A::A(std::string)'
 A(std::string apptype) : m_apptype(apptype)
 ^
Calender.cpp: In constructor 'A::A(std::string)':
Calender.cpp:10:38: error: 'apptype' was not declared in this scope
 A(std::string&& apptype) : m_apptype(apptype)
                                      ^

Upvotes: 0

Views: 1486

Answers (2)

HuskyDucky
HuskyDucky

Reputation: 1278

You need to instantiate your object A the replace the follow line

A(std::string("Test"));

to

A a(std::string("Test"));

I suppose you try to move the value passed to 'a' when you create an initialize with '&&', but you can't move the temporary string created by the function string() passed as parameter, then it won't compile too. You need to create a variable as shown below:

std::string S("Test");
A a(S);

But it always will make a copy of S and what you want is an object you can copy or move the string passed to it. The solution is make a move when you pass 'S' to 'a' as demonstrated below:

class A {
    public:
        A(const std::string apptype) : m_apptype(apptype) {
            std::cout << m_apptype;
        }

    private:
        std::string m_apptype;
};

int main() {
    std::string S("Test");

    A a(S);
    std::cout << (S.empty()?" moved":" copied") << " from S\n";

    A b(move(S));
    std::cout << (S.empty()?" moved":" copied") << " from S\n";

    return 0;
}

Upvotes: 0

Shrikanth N
Shrikanth N

Reputation: 652

First, you should create an object of class A A(std::string("Test")); is not creating an object of class A just calling parameterized constructor of class A.

You should instead change it to `A obj(std::string("Test"));.

Second, A(std::string&& apptype) : m_apptype(apptype) is not correctly implemented. The member initialization is trying to assign a string reference apptype to string object m_apptype which could lead to unexpected results.

Correcting, these should get it working considering the example you have shared.

Upvotes: 1

Related Questions