5

I have that common LNK2019 error and can not figure out what is wrong.

Here is my Solution Explorer:

enter image description here

Here is my Rectangle.cpp:

class Rectangle
{
    public:
        int getArea()
        {
            return this->width*this->height;
        }
        int width;
        int height;
};

Here is my Rectangle.h:

#pragma once
class Rectangle
{
    public:
        int getArea();
        int width;
        int height;
};

Here is my Functions.cpp:

#include <iostream>
#include "Rectangle.h";

using namespace std;

int main()
{
    Rectangle r3{ 2, 3 };
    cout << r3.getArea();

    return 0;
}

I am very new to C++ and it seems I did everything correctly, but still I am getting an error.

gsamaras
  • 71,951
  • 46
  • 188
  • 305
some1 here
  • 646
  • 1
  • 8
  • 18

2 Answers2

2

When you want to write the body of a class function, you need to write it this way :

#include "Rectangle.h"
int Rectangle::getArea()
{
    return this->width*this->height;
}

You do not need to redefine your class into the cpp file. You define everything inside the header (.h, .hpp), you include it inside the cpp file (#include "Rectangle.h") but you must not redeclare everything in the header file.

By the way, since you are writing a method, you can access member variables directly by width and you do not need to use this->width.

However, I recommand you to use a convention when you are writing your own classes. My convention is to prefix member variable by a m. (In your case it gives you mWidth or mHeight).

There is other people that have other conventions like m_variable or variable_.

Antoine Morrier
  • 3,930
  • 16
  • 37
  • So, in `.cpp` class file only an implementation of methods should go, am I right? – some1 here Aug 10 '17 at 16:12
  • @ohidano yes, that's right! Antoine, nice answer! :) – gsamaras Aug 10 '17 at 16:13
  • It depends on what you need. But I would say to process that way. One class = 2 files : one header like you do (it is a kind of plan) and the construction inside the *.cpp. After, it depends on what you need. But since you are beginning C++, I can advice you to do like we both said : header = class and prototypes of methods. cpp = implementation – Antoine Morrier Aug 10 '17 at 16:15
2

Rectangle.cpp should be like this:

#include "Rectangle.h"

int Rectangle::getArea() {
  return this->width*this->height;
}

You shouldn't redefine the class definition in the source file, since you already have it in the header file!

gsamaras
  • 71,951
  • 46
  • 188
  • 305