user1057741
user1057741

Reputation: 265

foward declaring class in namespace throwing compiler error

namespace chk{

class Car;
        Car abc()
        {
                return Car();
        }

class Car
{
        private:
                int sides;

        public:
                Car()
                {
                        std::cout<<"\ndefault called constructor";
                }
                Car(int nsides)
                {
                        std::cout<<"\ncalled constructor";
                        sides=nsides;
                }

                ~Car()
                {

                        std::cout<<"\nDeleting objext";
                }

};

       /* Car abc()
        {
                return Car();
        }*/
}

I am getting following error for above code :-

check.cpp: In function ‘chk::Car chk::abc()’:
check.cpp:25: error: return type ‘struct chk::Car’ is incomplete
check.cpp:27: error: invalid use of incomplete type ‘struct chk::Car’
check.cpp:24: error: forward declaration of ‘struct chk::Car’


Now when uncomment the below abc() and comment above abc() then it works fine. Why c++ is not allowing me to forward declare class inside namespace?

Upvotes: 0

Views: 111

Answers (2)

kfsone
kfsone

Reputation: 24249

The problem is that your abc() function needs the complete definition of Car.

Car abc() { return Car(); }

Not least here is the requirement that it has to know the definition so it can determine which constructor this would resolve to.

Forward declaration only covers cases where you need a pointer or a reference to a type, it does not cover cases where you need to resolve internal details.

Figuring out which constructor to use is an internal detail. In addition, the compiler also needs to know how big a "Car" object is going to be in order to return one as you are returning it by value.

One way to solve this would be to forward declare the function:

class Car abc();

class Car { ... };

Car abc() { return Car(); }

Upvotes: 1

juanchopanza
juanchopanza

Reputation: 227390

Why c++ is not allowing me to forward declare class inside namespace?

What C++ does not allow is to have a function such as

Car abc()
{
    return Car();
}

without class Car's definition. This is needed because a) the size of a Car object is required, and b) there is a call to the default constructor of the class. Without the class definition, there is no way to know whether the constructor exists or not.

Upvotes: 1

Related Questions