1

I tried to start to code in C++ after a long time.
I started a little project and got an error after little time :(

I have two classes: MyClass and OtherClass (just as an example)

My main.cpp:

#include "MyClass.h"
#include "OtherClass.h"

int main(){
    OtherClass* otherClass = MyClass::doSomething();

    return 0;
}  

OtherClass.h:

#pragma once
class OtherClass
{
public:
OtherClass(int a, int b, int c);
~OtherClass();

private:
    int a, b, c;
};

OtherClass.cpp:

#include "OtherClass.h"

OtherClass::OtherClass(int a, int b, int c)
{
    this->a = a;
    this->b = b;
    this->c = c;
}

OtherClass::~OtherClass(){}

MyClass.h:

#pragma once
#include "OtherClass.h"

class MyClass
{
public:
    static OtherClass* doSomething();

private:
    MyClass();
    ~MyClass();
};

MyClass.cpp:

#include "MyClass.h"

MyClass::MyClass(){}
MyClass::~MyClass(){}

OtherClass* doSomething(){
    return new OtherClass(0, 0, 0);
}

For me everything seems fine.
I'm used to code in C# so maybe I'm missing something important (I guess because I'm getting this error).

The error I get:

Error   1   error LNK2019: Unresolved external symbol ""public: static class OtherClass * __cdecl MyClass::doSomething(void)" (?doSomething@MyClass@@SAPAVOtherClass@@XZ)" in function "_main". D:\Projects\TestProject\main.obj    TestProject

Hope you can help me :)

0

3 Answers 3

4

In MyClass.cpp, the function:

OtherClass* doSomething(){
    return new OtherClass(0, 0, 0);
}

Should be qualified with a class name:

OtherClass* MyClass::doSomething(){
    return new OtherClass(0, 0, 0);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Oh no. I always read OtherClass* MyClass::doSomething() and had this signature in my mind but I haven't written it to "paper" :D Hate these situations. Thanks :) I'll choose this answer as soon as the system lets me do it :) First come, first served. Thanks to the other posters, too :)
2

Your problem is the definition of doSomething(): you defined a global function rather than a member function:

OtherClass* doSomething(){
    return new OtherClass(0, 0, 0);
}

You meant to write

OtherClass* MyClass::doSomething(){
    return new OtherClass(0, 0, 0);
}

Comments

1

In your definition, you forgot MyClass::

OtherClass* MyClass::doSomething(){
    return new OtherClass(0, 0, 0);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.