0

Please see my previous post here:

Undefined type error even with forward declaration

I moved the definitions to cpp files and I still face the issue. Any ideas why? My files look like this:

Header1.hpp

#ifndef HEADER1_HPP
#define HEADER1_HPP

namespace sample_ns
{
    class sample_class{
    public:
        static int getNumber();
        static void print();    
    };
}
#endif

Header2.hpp

#ifndef HEADER2_HPP
#define HEADER2_HPP
namespace sample_ns
{
    class sample_class2{
    public:
        sample_class2();
        int getNumber2();
    };
}

#endif

Source1.cpp

#include "Header1.hpp"
#include "Header2.hpp"
#include "stdafx.h"
#include <iostream>
namespace sample_ns
{
        int sample_class::getNumber()
        {
            sample_class2 obj;
            return obj.getNumber2();
        }
        void sample_class::print()
        {
            std::cout << "Print utility function" << std::endl;
        }
}

Source2.cpp

#include "Header2.hpp"
#include "Header1.hpp"
#include "stdafx.h"
#include <iostream>
namespace sample_ns
{
        sample_class2::sample_class2()
        {
            sample_class::print();
        }
        int sample_class2::getNumber2()
        {
            sample_class::print();
            return 5;
        }
}

In my main I call it as:

 std::cout << sample_ns::sample_class::getNumber() << std::endl;

I get 'sample_class2' : undeclared identifier. I tried adding class sample_class2; but that still gives me error

EDIT: my main file:

#include "stdafx.h"
#include <iostream>
#include "Header1.hpp"

int _tmain(int argc, _TCHAR* argv[])
{
    std::cout << "hello" << std::endl;
    std::cout << sample_ns::sample_class::getNumber() << std::endl;

    return 0;
}
Community
  • 1
  • 1
ashish g
  • 429
  • 1
  • 7
  • 16

1 Answers1

0

The best practice for declaring classes and namespaces in header and cpp files is using structure likes below:

Header1.hpp

#ifndef HEADER1_HPP
#define HEADER1_HPP
#include "Header2.hpp"
#include <iostream>

namespace sample_ns
{
    class sample_class{
    public:
        static int getNumber();
        static void print();    
    };
}
#endif

Source1.cpp

#include "Header1.hpp"
namespace sample_ns
{
        int sample_class::getNumber()
        {
            sample_class2 obj;
            return obj.getNumber2();
        }
        void sample_class::print()
        {
            std::cout << "Print utility function" << std::endl;
        }
}

So by including in header files and using ifndef you become sure that circular dependencies will not occure.

JGC
  • 12,737
  • 9
  • 35
  • 57