C++ Set an object as default argument (which is a reference) [duplicate] - c++

This question already has answers here:
Non-const reference bound to temporary, Visual Studio bug?
(2 answers)
Use a temporary as default argument in constructor
(4 answers)
Closed 4 years ago.
I have been looking for a reply for this a lot, but I cannot find nothing. My compiler doesn't give me any error or warning, but maybe there could be any danger into doing this:
class Dog
{
Dog(): x(0) {}
int x;
};
If I have a simple class, creating a function in another class like this:
class PetHouse
{
void addDog(Dog& animal = Dog())
{
// Anything...
}
};
Is the addDog() declaration right? I have an argument which is a reference and it's default value is a Dog() object, instead an existing object.
Is there any danger?
Thanks for reading!

No, it isn't. It should not even compile, because non-const lvalue references do not bind to temporaries like Dog().
As #StoryTeller hints, you are probably using MSVC without /permissive-.

Related

Object creation with parameters not possible in c++? [duplicate]

This question already has answers here:
Why can't member initializers use parentheses?
(2 answers)
Initialization of member variable via parentheses doesn't work [duplicate]
(1 answer)
can not define and init a class member by Parentheses [duplicate]
(1 answer)
Closed 9 months ago.
I'm trying to neatly create a objects within a class and I've run into what seems to me to be an odd limitation in c++, and I wondered if I'm just missing a syntax trick or whether it's truly impossible; specifically it seems like I cannot explicitly instantiate a class object inside another class if the constructor of the former has parameters (the parameters are constant) generating the odd message: 'Expected parameter declarator'
It seems as though only default constructors are supported in this scenario, or am I missing a bit of magic?
Currently using c++17 (simply because that's the default in this IDE)
class Fred
{
public:
Fred(const int i)
{
}
Fred()
{
}
};
Fred fred1(0); // This compiles
class Charlie
{
Fred fred2(); // This compiles
Fred fred3(0); // This does not compile
};

Compiler Error C2758 in Visual Studio 2013 [duplicate]

This question already has an answer here:
Using references to access class objects C++
(1 answer)
Closed 7 years ago.
I have this lines:
class ModulePeople : public Module {
public:
std::list<People> & list_people;
std::list<People>::iterator it;
}
When I try to compile I have this error:
Compiler Error C2758
'ModulePeople': a member of reference type must be initialized
This error appears in this line for example:
it = list_people.begin();
But I don't really know how to inicializate this kind of variable, because i can't do it to NULL. If somebody can help me it would be very grateful.
A reference is an alias for an existing object with storage space somewhere. This means that a reference must reference (no pun intended) an existing object, it's not like a pointer which can has value of nullptr.
This implies that if you use a reference as a member field of a class definition then you must initialize it through any available constructor of such object, eg:
class ModulePeople : public Module {
public:
std::list<People> & list_people;
std::list<People>::iterator it;
ModulePeople(decltype(list_people) list_people) : list_people(list_people) { }
}
If you really want to be able to let it point to nothing then could use a pointer instead, eg std::list<People>*.

unexpected compilation error when passing by reference anonymous instance [duplicate]

This question already has answers here:
How come a non-const reference cannot bind to a temporary object?
(11 answers)
Closed 7 years ago.
Let's say I have a struct :
struct structazauras
{
string bla;
}
And some function (in my case this function is actually a constructor of some class but I don't think this is the issue):
void myfunc(structazauras& mystruct) { }
then some where i call myfunc :
..
myfunc(structazauras());
..
I get an error:
no matching function for call to myfunc(structazauras) candidates are myfunc(structazauras&)
If I change the code to :
structazauras tmp;
myfunc(tmp);
It will work fine.
I feel that he (the compiler) has a problem passing a reference to the anonymous instance if structazauras, but why ? the anonymous instance exist on the stack of the calling function.
That is because you cannot bind a temporary to a non-const reference. Mark your reference as const and it will work.
Also, you are using a standard C++ keyword (struct) in the definition
void myfunc(structazauras& struct) { }
Change the name to something else. Or maybe you meant
void myfunc(struct structazauras&) { }
but the additional struct is superfluous in C++.

Constructors C++, What does the colon after a constructor mean? [duplicate]

This question already has answers here:
C++, What does the colon after a constructor mean? [duplicate]
(6 answers)
Closed 8 years ago.
Skimming through some code I noticed something I honestly can't wrap my head around in a constructor.
class Terrain
{
public:
Terrain(int movementCost,
bool isWater,
Texture texture)
: movementCost_(movementCost),
isWater_(isWater),
texture_(texture)
{}
... //More code
What sort of wizardry is this? Are those foo_(foo) representing foo = foo_?
This is a c++ initialiser list.
You have it almost right, foo_(foo) is equivalent to foo_ = foo;
This is useful for when you have a member variable that does not have a default constructor.
Without this feature, you would have to make it a pointer.
The initialisations are also executed in the order that the members were declared in the class defenition, not the order they appear in (which should be the same as a matter of style, but isn't necessarily)

Why is there no call to the constructor? [duplicate]

This question already has answers here:
Default constructor with empty brackets
(9 answers)
Closed 4 years ago.
This code doesn't behave how I expect it to.
#include<iostream>
using namespace std;
class Class
{
Class()
{
cout<<"default constructor called";
}
~Class()
{
cout<<"destrutor called";
}
};
int main()
{
Class object();
}
I expected the output 'default constructor called', but I did not see anything as the output. What is the problem?
Nope. Your line Class object(); Declared a function. What you want to write is Class object;
Try it out.
You may also be interested in the most vexing parse (as others have noted). A great example is in Effective STL Item 6 on page 33. (In 12th printing, September 2009.) Specifically the example at the top of page 35 is what you did, and it explains why the parser handles it as a function declaration.
No call to constructor
Because the constructor never gets called actually.
Class object(); is interpreted as the declaration of a function object taking no argument and returning an object of Class [by value]
Try Class object;
EDIT:
As Mike noticed this is not exactly the same code as what you are feeding to the compiler. Is the constructor/destructor public or is Class a struct?
However google for C++ most vexing parse.
You can use it like this:
Class obj;
//or
Class *obj = new Class(/*constructor arguments*/);