Forward declaration of class

closed account (D1AqM4Gy)
How would I go about forward declaring this class so i can use it in and cpp file?

test.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include "test.h"

Test::Test()
{
    std::cout << "Constructor" << std::endl;
}

Test::~Test()
{
    std::cout << "Destructor" << std::endl;
}

void Test::Start()
{
    std::cout << "It Worked!" << std::cout;
}


test.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#ifndef TEST_H_INCLUDED
#define TEST_H_INCLUDED

class c_Test;

class Test : public c_Test
{ // Error
public:
    Test();
    ~Test();
    void Start();
};

#endif 


main.cpp
1
2
3
4
5
6
7
8
9
#include <iostream>
#include "test.h"

int main()
{
    Test t;
    t.Start();
    return 0;
}


I've been trying to look around but I cant seem to figure it out. Error I get is: C:\Programs\CodeBlocks\Projects\test\test.h|7|error: invalid use of incomplete type 'class c_Test'|. I'm just trying to figure out how to use a class in multiple files. Can anyone help me?
Last edited on
closed account (zb0S216C)
The error message says it all. The declaration of "c_Test" only tells the compiler that the name "c_Test" now exists and to reserve it. However, the declaration does not inform the compiler what functions, data-members, constructors, destructor and operators it has.

When deriving from a class, "c_Test" in this case, the compiler needs all the class' information before deriving from it. The compiler needs to know how big the class is, it needs to know if "c_Test's" constructors/destructor can be called and also needs to know if the class has a virtual-table. As state above, a forward declaration only introduces a name.

In conclusion, before deriving from a class, ensure that the class is defined beforehand.

Wazzak
closed account (D1AqM4Gy)
Ok I understand what i was doing wrong. I looked at another one of your posts here: http://www.cplusplus.com/forum/beginner/62992/

I was trying to do the same exact thing and apparently I needed to add the file to the project. Which is weird because I thought they were added automatically when i made a new file in Code::Blocks. Anyway, thank you for the help, Framework.

EDIT:

If it really matters here was the fix

main.cpp
1
2
3
4
5
6
7
8
9
#include <iostream>
#include "test.h"

int main()
{
    Test t;
    t.Start();
    return 0;
}


test.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include"test.h"

Test::Test()
{
    std::cout << "Constructor" << std::endl;
}

Test::~Test()
{
    std::cout << "Destructor" << std::endl;
}

void Test::Start()
{
    std::cout << "It Worked!" << std::endl;
}


test.h
1
2
3
4
5
6
7
8
9
10
11
12
#ifndef TEST_H_INCLUDED
#define TEST_H_INCLUDED

class Test
{
public:
    Test();
    ~Test();
    void Start();
};

#endif 
Last edited on
Topic archived. No new replies allowed.