0

I'm starting with C++ and I'm trying to create a class program, however, when I try to run it appears the error: C++: Undefined reference to 'NameSpace::Class::Constructor. The code is shown below:

Header for ClassA:

//ClassA.h
#ifndef CLASSA_H 
#define CLASSA_H
#include <string>

namespace ClassANameSpace
{
    class ClassA
    {
    private:
        std::string attribute1;
        double attribute2;

    public:
        ClassA();
        ClassA(std::string pAttribute1, double pAttribute2);

        void setClassA(std::string pAttribute1, double pAttribute2);
        
        std::string getAttribute1() { return attribute1; }
        double getAttribute2() { return attribute2; }

    };
}

#endif 

Class A:

//ClassA.cpp
#include "ClassA.h"
using namespace ClassANameSpace;

ClassA::ClassA()
{

}

ClassA::ClassA(std::string pAttribute1, double pAttribute2)
{
    setClassA(pAttribute1, pAttribute2);
}

void ClassA::setClassA(std::string pAttribute1, double pAttribute2)
{
    attribute1 = pAttribute1;
    attribute2 = pAttribute2;
}

Main:

// main.cpp
#include <iostream>
#include "ClassA.h"
using namespace std;
using namespace ClassANameSpace;

int main(int argc, char const *argv[])
{
    ClassA classA ("string", 1.0);
    return 0;
}

When I try to run it appears: undefined reference to `ClassANameSpace::ClassA::ClassA(std::__cxx11::basic_string<char, std::char_traits, std::allocator >, double)'

Someone can guide me to undestand what is going on?

  • 1
    Please show how do you compile your code. – Yksisarvinen Apr 14 '21 at 15:31
  • 2
    And offtopic, but what's the point of adding namespaces if you abolish it in every file with `using namespace`? – Yksisarvinen Apr 14 '21 at 15:31
  • Does this answer your question? [What is an undefined reference/unresolved external symbol error and how do I fix it?](https://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix) – Stephen Newell Apr 14 '21 at 15:35
  • 1
    How are you compiling this? I just tried with: `g++ -std=c++11 main.cpp ClassA.cpp` and it compiled and ran fine. – Patrick Apr 14 '21 at 16:12
  • I am using Visual Studio Code and I dont know how to compile it correctly, however, now I im trying with codeblocks and it works. Someone knows where can I look for the right way to compile in VSC? Thank you very much! – SnowArtz Apr 14 '21 at 16:15
  • @SnowArtz Please update your question now that you know more. – Joseph Larson Apr 15 '21 at 05:16

0 Answers0