Reputation: 11
I have a project where I need to expand some functionality without touching the project I'm using.
The core of the problem is this (I dumbed it down but the core should be clear).
//Layout.h
#ifndef LAYOUT_H
#define LAYOUT_H
#include "Speaker.h"
class Layout
{
public:
//unrelated stuff
private:
LSS::Speaker temp;
};
#endif
//Speaker.h"
#ifndef SPEAKER_H
#define SPEAKER_H
namespace LSS
{
struct Speaker
{
Speaker(int val1, float val2)
:some_int(val1)
, some_float(val2)
{
}
~Speaker()
{
//do other stuff
}
int some_int;
float some_float;
};//struct Speaker
}
#endif
I just want to be able to use the struct Speaker (as defined in "Speaker.h") in "Layout.h" without touching "Speaker.h"
If I compile I get following errors:
Error 22 error C2512: 'LSS::Speaker' : no appropriate default constructor > available Layout.cpp 7 1 MyProj
I think that wraps it up - any help would be appreciated, I'm pretty new to c++
Edit: in recreating the issue I made a TYPO (LSS: instead of LSS::). Updated the compiler error
Upvotes: 0
Views: 106
Reputation: 254431
To answer the new question, now it's been changed to invalidate previous answers:
'LSS::Speaker' : no appropriate default constructor
As the error message says, the class has no default constructor, so it can only be instantiated by providing constructor arguments. You probably want to do this in the Layout
constructor(s), for example:
Layout() : temp(some_value, some_other_value) {}
Upvotes: 0
Reputation: 6407
Read carefully message
Error 3 error C2146: syntax error : missing ';' before identifier 'temp' > Layout.h 102 1
and then change LSS:Speaker temp;
to LSS::Speaker temp;
EDIT:
For error
Error 22 error C2512: 'LSS::Speaker' : no appropriate default constructor > available Layout.cpp 7 1 MyProj
if you provide at least one constructor with parameters for Speaker, you also have to provide default constructor (constructor without parameters) to make LSS::Speaker temp;
valid. It is a rule (for cases when no constructors are written by programmer compiler make default constructor, but if programmer start changing construction logic, compiler do nothing in this part of work).
Or you can provide default values in the existing constructor, like this:
Speaker(int val1 = 0, float val2 = 0.0f)
:some_int(val1)
,some_float(val2)
{
}
Upvotes: 1
Reputation: 11
I figured out how to work around Layouts.h not having a default constructor (remember: in this case I wasn't allowed to edit the Speaker() struct)
In Layout.h I defined
class Speaker: public LSS::Speaker
{
public:
Speaker(): LSS::Speaker(-1, 0.0f){}
};
'Overloading' the missing constructor (that I couldn't fill in myself.
Problem solved :)
Upvotes: 0