I have a very basic problem, which answer is not covered in the 1200 pages of the C++ book I'm using to teach myself.

Consider this simple code:

#include "stdafx.h"

using namespace System;

class EventListener
{
    long mRef;
 public:
    EventListener()
    {
        mRef = 0;
    }
};

int main(array<System::String ^> ^args)
{
    Console::WriteLine(L"Hello World");
	EventListener *listener = new EventListener();
    return 0;
}

That compiles in Visual Studio without problems.

But if I move:

#include "stdafx.h"

using namespace System;

class EventListener
{
    long mRef;
 public:
    EventListener()
    {
        mRef = 0;
    }
};

in a different source file keeping only:

#include "stdafx.h"

using namespace System;


int main(array<System::String ^> ^args)
{
    Console::WriteLine(L"Hello World");
	EventListener *listener = new EventListener();
    return 0;
}

in the first main file, the compiler does not find the EvenListener class.

How do I make a class defined in a given file available to functions defined in other files?

Thanks.

Recommended Answers

All 2 Replies

I'd suggest reading up on "header" files.

To assist, rename the following code into a file named EventListener.h

#include "stdafx.h"

using namespace System;

class EventListener
{
    long mRef;
 public:
    EventListener()
    {
        mRef = 0;
    }
};

Rename the following as main.cpp and add the following line #include "EventListener.h" as follows

#include "stdafx.h"

using namespace System;
#include "EventListener.h" // here

int main(array<System::String ^> ^args)
{
    Console::WriteLine(L"Hello World");
	EventListener *listener = new EventListener();
    return 0;
}

Rename the following as main.cpp and add the following line #include "EventListener.h" as follows

Duh, I was seing a class as an external routine (I'm used to C, not yet to C++) rather than as a definition.

Thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.