Reputation: 4006
I am having an issue with this error, and adding a default constructor does not fix it. compiling without default constructors produces the error, compiling with default constructors produces the error. I've been searching online for hours but found nothing. Here's a quick example of my code (The actual code is rather long):
//Header.h
using namespace std;
class BaseClass;
class DerivedClass;
BaseClass *MyClass = new DerivedClass;
class BaseClass
{
virtual void myFunction()
{
cout << "Base Class";
}
};
class DerivedClass : public BaseClass
{
void myFunction()
{
cout << "Derived Class";
}
};
//Main.cpp
#include <iostream>
#include "Header.h" //I believe this gives Header.h access to iostream
//I believe it cause it works
using namespace std;
int main()
{
cout << "Hello";
}
The error is in Header.h, Main is only there to give Header.h access to iostream. As I said I've look for HOURS. And haven't found any ways to fix the error: Error C2512: 'DerivedClass' : no appropriate default constructor available
Upvotes: 0
Views: 925
Reputation: 310990
You program is totally invalid.
You allocate memory for class DerivedClass but it is not defined yet.
Baseclass *MyClass = new DerivedClass;
You use standard output stream
cout << "Base Class";
but it is not declared yet because there is no the corresponding header where the stream is declared.
The definition of function myFunction has no sense because it has private access control and may not be called outside methods of the class itself but there is no such a method.
The correct code could look the following way
//Header.h
#include <iostream>
using namespace std;
class BaseClass
{
public:
virtual void myFunction() const
{
cout << "Base Class";
}
};
class DerivedClass : public BaseClass
{
public:
void myFunction() const
{
cout << "Derived Class";
}
};
//Main.cpp
#include <iostream>
#include "Header.h" //I believe this gives Header.h access to iostream
//I believe it cause it works
using namespace std;
Baseclass *MyClass = new DerivedClass;
int main()
{
cout << "Hello";
}
Upvotes: 0
Reputation: 9097
Baseclass *MyClass = new DerivedClass;
should come after the definition of the classes, i.e. end of file
P.S. your comment in the code (about giving access to iostream) is correct. But consider it is not good practice. Header files should compile with no requisites on different inclusions.
instantiating the MyClass
object within the .h is no good practic either.
Upvotes: 0
Reputation: 4738
Why you need this in header file?
Baseclass *MyClass = new DerivedClass;
Clearly compiler is looking for definition of derived
class and not found till this line executes.
Move it after implementation of derived
class or in main
.
Upvotes: 1