No matching function for call to...? - c++

I'm getting an error for what I assume is declaring the incorrect type, but I'm not sure where the issue is or what I need to fix. I'm using two files.
Please tell me if I haven't given enough info, I'm still a newbie. I'd really appreciate the help.

I appreciate you can't change the input for the test, but whoever wrote the test needs to be told it's a bad test.
Data should be initialized through a constructor.
Data members (address and price) should be declared as private not public.
Whoever wrote the test is requiring you to write a bad C++ class.
That said, you can conform with this bad test by adding to the .h file:
HousePrice();
and to the .cpp file
HousePrice::HousePrice():address(""),price(0){}
Thereby giving it the expected default constructor.

Change it to
#include "zillow.h"
HousePrice hp ("1600 Pen. Ave",1561.53);
ASSERT_EQ(hp.price, 1561.53);
Previously you were trying to create your HousePrice object with no constructor parameters, but the only constructor you've written takes address and price.

The error is here:
HousePrice hp;
When you create an object of a class like that, the default constructor of the class is invoked implicitly. But your class definition does not have a default constructor.
Solution:
Since you are not allowed to change the code at the caller's part, you should modify your class definition such that it contains a default constructor. Then it is upto you to decide the initial values or simply leave it empty.
For example:
Add HousePrice() inside the class definition in zillow.h
Add the following into zillow.cpp
HousePrice::HousePrice()
{
address = "";
price = 0.0;
}

The answer is in the error message. You are trying to default-construct an object of HousePrice type, but HousePrice does not have a default constructor.
Add a default constructor (a constructor with no parameters)
Side note: there is no point in having getter or setter functions in this example. Your data members are public and you don't have any constraints on them

Related

C++ passing object to function by refrence, its constructor get called

I'm trying to figure out how to use multiple files properly. I made a class in the header file. Then a cpp file that included that header file and implemented everything with Stage::Stage(){} etc. I also made a class called Display that has no default constructor, but requires 2 integer arguments. I made a function in Stage class:
Stage::Stage (Display &display_){
display = display_;
}
But it causes an error "no matching function for call to 'Display::Display()'"
Which is true, it doesn't exist, but it shouldnt need to exist. I'm not trying to create a new Display object here, I'm trying to pass an existing one to the Stage object. (I'm using Dev C++)
Your Stage constructor must default-initialize display before executing the body of the constructor. All class members must be constructed before executing the body of the class's constructor. No exceptions. The shown code, therefore, attempts to default-construct display before using the assignment operator on it.
Since Display does not have a default constructor, this fails, hence the complaint from your compiler that there is no defualt constructor.
In this situation you must explicitly construct display in the initialization section of the constructor:
Stage::Stage (Display &display_) : display{display_}
{
}
or, pre-C++11:
Stage::Stage (Display &display_) : display(display_)
{
}
This explicitly constructs the display member right from the beginning, presumably using its copy-constructor.

Making default constructor private in Qt custom object

I'm reading this Qt doc page about custom types, and it states the following:
The default constructor, copy constructor and destructor are all required, and must be public, if the type is to be integrated into the meta-object system.
Suppose I have an object that needs to be built with some required parameters, because it has no sense to be built using the default constructor, for example:
struct IntPair
{
IntPair(int first, int second);
~IntPair();
};
To make it available in the Qt Meta Object system, as the doc states, it requires the default constructor. But practically, it has no sense to give the opportunity to build an IntPair object without a pair of integer numbers (sorry for the ugly example).
Is there a way to achieve this without implementing the default constructor? I'm thinking about a sort of friendship between my object and the Qt Meta Object system...
Basically, I cannot understand why the default constructor is needed.
There are two parts to the question:
Achieving a custom Meta Object without implementing a default ctor.
Understanding why a default ctor is required by Qt in this case.
Other respondents have addressed (2) already.
I wish to address (1).
I wrote a class, and I intend for users of this class to call a ctor I wrote which requires several arguments. However, because of the Qt-related requirements, I am forced to add a zero-argument constructor.
It would make me happy to at least make the zero-arg ctor private, so that I could enforce that all user code EXCEPT moc-generated "magic" code will be barred from using that ctor.
Hello, happiness! It is possible.
You can indeed use friendship to make the default ctor private and still use Qt Metatype.
It looks something like this:
class MyClass {
Q_GADGET
Q_PROPERTY(QString text READ text)
public:
MyClass(QString text, bool sometruth, int someint);
QString text() const { return text_; }
private:
// Works in my project using Qt 5.12. (see hints below if it fails for you)
friend struct QtMetaTypePrivate::QMetaTypeFunctionHelper<MyClass, true>;
// Prefer the ctor that takes arguments. This ctor only exists to satisfy Qt.
MyClass();
QString text_;
};
There are two ways you can solve the problem of figuring out WHAT to befriend.
You can mark the ctor private, try to recompile, and scrutinize the compiler error to figure out what other type is trying to access the ctor of your class.
Or, you can put an assert(false); in the body of your ctor, create a binary with debug symbols (including Qt debug symbols), then look at the stack in the debugger when the assertion fails. The stack will show the Qt-internal member-function or free function that called into your ctor. Friend whatever that caller is.
This last method (using the debugger) is what worked for me. (I wasn't fluent enough in compiler-ese to discern which type from the output of the gigantic compiler error was what I needed to add as my friend.)
It has to do with QVariant's (templated) implementation.
Look at qvariant.h in the QT5.5 source code tree, and you'll find this:
T t;
if (v.convert(vid, &t))
return t;
return T();
And also:
old->~T();
new (old) T(t); //call the copy constructor
Hence the need for a public constructor/desctructor, and copy-constructor.
The advantage of all of this is being able to use your custom type in signals/slots (and other meta-object magic), but there are drawbacks like in your situation. It's just a trade-off that you have to live with.
As a workaround, you could have some sort of "init()" method that actually initializes the object after it's constructed. Not as safe/elegant, but it works.
As to why, there's a design reason behind it. It involves a "Identity vs Value" discussion that I think is too long to paste here.
As to how, #AlexanderVX commented on using default values in arguments.
Custom data type should have public default constructors because many parts of the Qt framework will call it to avoid returning null pointers. E.g. QVariant and containers accessors (e.g. QHash::value()).
In your case IntPair() : IntPair(0,0) { } should be nice, isn't it ?
In many cases it is convenient to hold data in objects impementing Qt's implicit sharing pattern (see http://doc.qt.io/qt-5/implicit-sharing.html), in which case the default constructor may easily initialize with QSharedDataPointer(0) and every accessor return a default value when pointer is null (e.g. 0 for an int, QString() for a QString, etc.), guess what: every accessor will be able to provide a default value by calling the public default constructor of the data type because it is required to have one :-).

C++ construct asks for a struct that is not defined in .h

I have to do some changes in a project so I have to change some classes. This code was made by another person and I found a really weird problem doing my task (or at least trying until this wild mushroom appeared )
I have the next ClassA.cpp and I want to remove the m_ElemVar(enumType):
CClassA::CClassA(): m_iIntVariable(0), m_fFloatVar(0.0f), m_ElemVar(enumType1)
{
// more variables initizalized there
otherVariable = value;
...
}
the .h :
#include "CMyElement"
class CClassA
{
public:
CClassA();
virtual ~CClassA();
private:
CMyElement m_ElemVar; // THIS is the var
int m_iIntVariable;
float m_fFloatVar;
...
}
So the thing is that I don't want the m_ElemVar(enumType1) there because I will initialize it in another place, BUT if I remove it, when I build the class or the project it says:
error: no matching function for call to ‘CMyElemnt::CMyElemnt()
candidates are CMyElemnt::CMyElemnt(enumTypeName)
while if I remove the m_fFloarVar for example it doesn't complains.... That confuses me a lot because as you can see in the .h there is nothing declared so I understand that this constructor should not expect anything.
I've clean and build it again, and also searched into google but nothing found so any help would be very appreciated. Thank you so much
Looks like CMyElemnt does not have a parameterless constructor so you have to call one that takes the enum. Maybe you could reassign it later if you cannot change its interface.
The issue you are having is all objects of a class must be constructed in order for the class to be constructed. If you don't construct one of the member explicitly then the compiler will do it for you implicitly using the default constructor. Since CMyElemnt does not have a default constructor you will get an error. The reason not initializing m_fFloatVar works is it is a float and the compiler can default construct a float.
To look at a different way anything you can write as
some_type some_name;
Is default constructable. If you have do include parameters like:
some_type some_name(some_variables)
Then it is not default constructable and you need to initialize it yourself.

How To Initialize a Variable to Previously Allocated Memory?

I'm using C++, and am creating a ex_stage class (a SystemC module, if it makes any difference). In the header file for the class, I define:
public:
ReorderBuffer ROB;
Where ReorderBuffer is another class I have also defined, which has its own constructor. I have defined ROB as a global variable for the ex_stage class so that it can be accessed from multiple functions within ex_stage.
However, I cannot initialize ROB until runtime as it depends on user-supplied values for some of its functionality. So, even though I define ROB as a global variable, I cannot initialize it where it is defined.
Normally, I would do something like this:
ReorderBuffer ROB(<incoming variables>);
within the constructor of ex_stage to construct ROB at the same time. However, since I have already defined ROB, I'm not sure if I am able to do that without causing issues.
Will performing an operation like this actually affect ROB in its original scope, or will it create a new ROB with a scope local to the constructor of ex_stage?
P.S. - Sorry if this is hard to understand please let me know if you need more information.
When you want to initialize something global, you have to be careful about "Global initialization fiasco". If i were you, i would use an unnamed namespace to hide a global var pointer and have some global functions (just inside a named namespace) such as InitMyGlobalVar(), GetMyGlobalVar() to initialize and retrieve the pointer.
If you know how to initialize ROB when your ex_stage constructor runs, you might find a member initializer useful.
Member initializers allow class members to be initialized in a specific way, as opposed to just having their default constructors called:
class ex_stage {
public:
ex_stage() : ROB(<stuff>) {} // constructor that takes <stuff> will be called
ReorderBuffer ROB; // default constructor will _not_ be called
};

C++ object not working with dot operator

Hello I am working on a C++ program and I am just starting out by creating some sample objects out of the class that I created. I am creating the object but for some reason the dot operator is not working with the object
This is the object call
Card testcard(Suit hearts, Value six);
This is the constructor
Card::Card(Suit suit, Value facevalue)
{
Card::suit=suit;
Card::faceValue=facevalue;
};
However the dot operator is not working, as if the object is not really there
I am controlling most of the program in seperate parts so there are many instances of header files which is where the card class is located, I am not sure if that is part of the problem
From within an instance method, you can't use a dot to access the instance.
Try this-> instead:
Card::Card(Suit suit, Value facevalue)
{
this->suit=suit;
this->faceValue=facevalue;
};
Alternately, you can use an initializer list:
Card::Card(Suit suit, Value facevalue) : suit(suit), faceValue(facevalue)
{ }
Assuming the class looks something like:
class Card {
public:
Card (Suit argSuit, Value argFaceValue);
private:
Suit m_Suit;
Value m_FaceValue;
};
The constructor would look like this. Since the members of the class are available to the objects created from the class you do not need to do anything special to access them. The members of the class are within scope and are visible. You just need to make sure that the argument list of the function uses different symbols or names than the class/object members.
Card::Card(Suit argSuit, Value argFaceValue)
{
m_Suit = argSuit;
m_FaceValue = argFaceValue;
}
This is the object call
Card testcard(Suit hearts, Value six);
No, that's a function declaration. Naturally using the member access operator (.) on the name of a function doesn't work, the function has its own type which doesn't have members.
To declare an automatic variable (creating a new object instance), don't repeat parameter types. Just say:
Card testcard(hearts, six);
I think some of your naming conventions are causing some confusion for you. As pointed out above, you are running into a problem of context with the suit and facevalue arguments passed to the constructor. This means that in the context of the constructor method, suit really means the suit that is passed in as an argument, over the suit that is a member variable of the class Card. People generally use a naming convention to help avoid this confusion, such as putting an m_ in front of each data member for the class, such that suit would become m_suit. You can use whatever you like, but that way someone else code would know right away that m_suit was a data member.
Another point is that you can, and probably should, initialize the data member for a class prior to the code for the constructor is executed. This is called the "initialization list" and would be done as follows (assuming you changed over to the naming convention above).
Card::Card (Suit suit, Value facevalue)
: m_suit (suit), m_facevalue (facevalue)
{
// no code needs to go here
}
For efficiency reasons it is a good idea to get in this habit. Further, using the this pointer is generally not a good idea in a constructor. It's not illegal, but can get you into trouble.
As far as the dot operator not working, it wasn't clear from your question exactly where you were using the dot operator. If you are referring to the :: syntax above, that isn't really an operator, it is part of the C++ syntax indicating that you are dereferencing the class. That syntax would work if you had declared the suit and facevalue data members as static, but that is not what you wanted to do.
You mention that you are declaring the Card class in multiple header files -- that too is bad.