-3

I'm creating an object in main.cpp like this:

#include <string>
#include "class.hpp"

std::string param = "name";

int main(){
     Class object(param);
}

class.cpp:

#include <string>

class Class {
public:
    std::string name;
    Class(std::string name) {
        this->name = name;
    }
};

class.hpp:

#pragma once

class Class {
public:
    std::string name;
    Class(std::string name);
};

However, when doing this I receive:

undefined reference to `Class::Class(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>)'

BUT if I put the constructor implementation in the header like this:

#pragma once

class Class {
public:
    std::string name;
    Class(std::string name) {
        this->name = name;
    }
};

It works. But now my hpp and cpp files are identical except for the include statement I have at the top of class.cpp.

My question is, is this bad practice? It seems redundant and wrong. What am I missing here? Why do I need to put the implementation for a constructor in the header?

Brian
  • 4,518
  • 4
  • 16
  • 34
Squid
  • 77
  • 8

1 Answers1

2

You declared 2 classes with same name, your cpp is completely wrong. It does not contain implementation of constructor declared in hpp file, it declares another class and it's implementation. main.cpp includes hpp file and look for implementation which does not exists.

So at first never use reserved keywords as names! test.hpp:

#pragma once
#include <string>
class Test{
public:
    std::string name;
    Test(std::string name);
};

test.cpp:

#include "test.hpp"

Test::Test(std::string name)
{
    this->name = name;
}

In cpp file you don't have to declare class twice, only constructor implementation should be there

Jeka
  • 1,354
  • 14
  • 31