Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

declare the definition of a class separating from its body

Following code is in the same header file

#include <iostream>
               
        class B
        {
        public:
            void doSth()
            {  
                A::func(1);
            } 
        };

        class A
        {
        public:
            static void func(int a)
            {
                std::cout<<"a = "<< a <<std::endl;
            }
        };
  

If class A is defined after class B like above, the compiler will complain about ‘func’ is not a member ‘A’.

My question is, is there anyway to solve this issue without changing the order how class B and class A are defined? Like putting a declaration of class A somewhere above class B? Thanks.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you want B::doSth() to be declared and defined completely inside of B‘s class declaration, then you must move the full declaration of A ahead of B, eg:

#include <iostream>
               
class A
{
public:
    static void func(int a)
    {
        std::cout << "a = " << a << std::endl;
    }
};  

class B
{
public:
    void doSth()
    {  
        A::func(1);
    } 
};

Otherwise, if you don’t need B::doSth() to be completely inside the B class declaration then you can separate its declaration and definition, and then move the definition after the declaration of the A class, eg:

#include <iostream>
               
class B
{
public:
    void doSth();
};

class A
{
public:
    static void func(int a)
    {
        std::cout << "a = " << a << std::endl;
    }
};

inline void B::doSth()
{  
    A::func(1);
} 

Preferably, method definitions that are not inside their class declaration should be implemented in separate .cpp files instead, eg:

A.h

#ifndef A_H
#define A_H

class A
{
public:
    static void func(int a);
};

#endif

A.cpp

#include <iostream>               
#include "A.h"

void A::func(int a)
{
    std::cout << "a = " << a << std::endl;
}

B.h

#ifndef B_H
#define B_H

class B
{
public:
    void doSth();
};

#endif

B.cpp

#include "B.h"
#include "A.h"
               
void B::doSth()
{  
    A::func(1);
} 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading