Search code examples
c++oopprecompiled-headers

c++ is there a way of use properties allready declared in the header file inside implementation


I know it's a basic question, but I didn't find the answer anywhere.

Supose we have this header:

#pragma once;
#include "user.h"

class Teacher
{
public:
    float teachSkill = 0.01;
    void teach(User &user);
};

And a implementation like this:

#include "teacher.h"

class Teacher
{
public:
    float teachSkill;
    void teach(User &user)
    {
        user.knowledge += (*this).teachSkill;
    }
};

if we already declared that teachSkill property in the header, is there a way c++ compiler can understand that this property is in the header on an implementation like this:

#include "teacher.h"

class Teacher
{
public:
    void teach(User &user)
    {
        user.knowledge += (*this).teachSkill;
    }
};

Solution

  • You can simply write, in the implementation:

    void Teacher::teach(User &user)
    {
        user.knowledge += (*this).teachSkill;
    }
    

    No need to re-declare the class there.

    Furthermore, you don't need (*this), so it's simply:

    void Teacher::teach(User &user)
    {
        user.knowledge += teachSkill;
    }