What does this small chuck of code mean? [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have this chuck of code and I'd really appreciate if someone could help me out by giving some more information about what it is. I know a bit of coding, but not too much so please bear with me if this seems silly.
class A
{
public:
A();
};
int x, y, z;
A::A():
x(1),
y(2),
z(3)
{
//some code here basically more variable definition
}
What I don't get is this,
a function which is also the name of a class? Even if it works, but why would I want to do that?
what is up with the variable definition of x, y, z. I assume some constructors are being called, but what's wrong with defining them the normal way?
And what does do they being after the colon : but before the function definition signify?
Thank you. Much appreciated.

Really, a C++ tutorial is what you need, but here goes:
A "function" with the same name as the class is a constructor. There can be several of these, each taking different arguments. In this case, the constructor takes no arguments at all (and so is called a default constructor). Not all classes have a default constructor, but if you don't write any constructors of your own, then the compiler will create a default constructor for you.
The bit after the colon is a special bit of syntax used in constructors. It's called an initializer list. What happens is that before you get to the body of the constructor, the member variables listed are initialized with those values (or, in the case of objects, constructors are called with those arguments). You should always use an initializer list to set the values of variables if you can.
In this case then, the default constructor specifies that the member variables x, y and z should be initialized to 1, 2 and 3 respectively (at least I assume they're meant to be member variables -- as written, they're actually globals).

What you have in your question isn't valid C++.
class A
{
public:
A();
};
int x,y,z; // x,y,z are out here in the wild
// This is supposed to be the definition of the constructor of "A"
// outside the "A" class
//
// The "A::A() : " sequence introduces a list of member initializers.
A::A() :
x(1), // <- These are not members of "A", so they cannot be initialized as members!
y(2), // <-
z(3) // <-
{
}
What I think you meant was:
class A
{
public:
int x,y,z;
A();
};
A::A() :
x(1), // <- Now members of "A", so they can be initialized here
y(2), // <-
z(3) // <-
{
}

Related

Construction initializing the arguments in the constructor [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have a simple yet maybe stupid question. I was asked to point out the difference between two initializing ways. I am not really able to point out the difference. Could you help me?
A(int a);
A(int a=3);
Assuming A is a class or struct, then:
A(int a);
defines a converting constructor that requires the caller to provide an input value when creating an object instance of A, eg:
A a(12345); // OK
A a; // ERROR
Whereas:
A(int a=3);
defines a converting constructor that has a default parameter value, allowing the caller to omit passing in a value if desired, eg:
A a1(12345); // OK, will use a=12345
A a2; // OK, will use a=3
Since passing in an input value is optional in this constructor, it can thus also serve as A's default constructor as well, unless one is also defined, then this becomes ambiguous as to which constructor to call when no input value is provided, eg:
A();
A(int a = 3);
A a; // ERROR, ambiguity
In the first one you must provide the constructor an int.
A(int a);
In the second you can provide an int, but if you don't the default value for a will be 3.
A(int a = 3);
A(int a);
A(int a=3);
We can't declare the above constructor declaration together in the class.
Because compiler will say function already defined.
A(int a); is equal to A(int a=3);
For example if you have one constructor like as follows
A(int value=3) { a = value; cout << "\nOne Parameter Constructor" << " a="<<a; }
Object Creation:
A a1; A a2(6);
Output:
One Parameter Constructor a=3
One Parameter Constructor a=6

Constructors for variable types [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
This is a very basic question but for declaration of variables are constructors called?
int x; //Global variable
class A{
public:
int y;
A()
}
As it commented out, int is a POD (Plain Old Data) type.
A Plain Old Data Structure in C++ is an aggregate class that contains
only PODS as members, has no user-defined destructor, no user-defined
copy assignment operator, and no nonstatic members of
pointer-to-member type
Note that, a constructor is nothing but a member function. A member function must belong to a class and as we mentioned, int is just a built-in fundamental variable type, not a class. So to answer your question, there is no constructor called for the declaration of non-class types such as primitive data types, array types, pointer types and so on.
However, it may cause a misunderstood to see an initialization like this;
int var(10);
Even though it looks and acts so similar to a constructor, there is no constructor called there. It is just an initialization. int var(10); simply equals to int var = 10;.
First you have to understand that the built-in types don't have constructors; this is a privilege reserved for user-defined types (classes).
What you're really asking is whether a data member of type int will be zero-initialised by default, and the answer is no; they're "default-initialized", which leaves them with an unspecified value that cannot read.
You should initialize y yourself in the class constructor A() — that's what it's for! Assuming you wanted it to be zero:
class A
{
public:
int y;
A() : y(0) {}
};
Global variables are a bit different. What I wrote above is still basicaly true for those, but since they have static storage duration there is an "extra" step which makes all their bits zero before your program starts. This has the effect of making x initialised to zero despite the lack of explicit initializer, and you can rely on this.
The chapter about variable initialisation in your C++ book will go into greater detail about this.

C++ How does order of instance creation matter? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have a class that creates instances of other classes, and when I call them, compiler gives me warning about order of the instances. Why does it matter? It does same job, regardless of the order.
E.g. I have this in my core class header file (core class handles game loop):
HUD hud;
World myWorld;
Like this they do all they need to. But compiler gives a warning:
'Core::myWorld' will be initialized after [-Wreorder]|
Then if I put myWorld instance above the hud instance, it doesn't give me warning anymore. I was just wondering, how on earth does it matter which order they are in?
Warning is since, in constructor initializer-list you initialize World before HUD, but actually members will be initialized in order they are declared in class.
Just litle example, where it can be worse:
class B
{
public:
B(int i) : value(i) {}
private:
int value;
};
class A
{
public:
A() : value(10), b(value)
{
}
private:
B b;
int value;
};
Here b will be initialized before value and so, something will be sended to b constructor, but not 10 as programmer want.
With
struct C
{
C() : p(std::make_unique<int>(42)), j(*p) {} // initialization doesn't use this order.
// but the order here:
int j;
std::unique_ptr<int> p;
};
you will dereference nullptr as j is initialized before p.

C++11, is default member construction a good thing? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Since C++11 we can default construct our variables in a class, like this:
class Foo{
private:
int bar = 0;
};
I've very rarely seen someone using this feature
Is this a good practice ?
This is a style question, but there are some considerations that are hopefully universal:
If all constructors of your class have to initialize a member the same way, because the initial value is in some profound way part of the invariants of the class, then it is both more readable and self-documenting and also shorter to use the inline initializer, and the deduplication removes a source of errors if you ever need to change the initial value.
Otherwise, if different constructors supply different initial values, then you shouldn't have an inline initializer, even though that's technically permitted.
I dont see any bad practices in this approach. This is allowed even in Higher level languages like Java. It reduces lines of code inside constructor.
The only big disadvantage I see is that it may lead people to expose more implementation details than necessary in class definitions. Currently, if you initialize a member in MyClass.cpp, then you can easily change the value later on. If you initialize the member in MyClass.h, then a lot of recompilation could be necessary if you later change the value.
In Java, you don't have this kind of separation between header and implementation, so the situation cannot be compared to C++.
C++11 allows non-static data members to be initialized in-class.
This can often save some typing. Consider the following example:
class Foo {
public:
Foo() : a_{5}, b_{7}, s_{"Foo"}, bar_{"Test"} {}
Foo(int x) : a_{x}, b_{7}, s_{"Foo"}, bar_{"Test"} {}
Foo(double d) : a_{5}, b_{g(d)}, s_{"Foo"}, bar_{"Test"} {}
int someFunc();
private:
int a_;
int b_;
std::string s_;
Bar bar_;
};
Using in-class initialization will IMHO make the code more readable.
class Foo {
public:
Foo() = default;
Foo(int x) : a_{x} {} // Initialization list overrides in-class initialization.
Foo(double d) : b_{g(d)} {} // Same here.
int someFunc();
private:
int a_ = 5;
int b_ = 7;
std::string s_{"Foo"};
Bar bar_{"Test"};
};
I would say use it when possible. An exception is when the situation described in this answer applies.

What is the better way to define a construtor in C++?Initialization list or Initialization in Ctor Body? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Initializing in constructors, best practice?
Advantages of using initializer list?
I have the following two ways to define the constructor in the Point Class :
class Point
{
public :
Point(double X,double Y):x(X),y(Y){}
Private :
double x,y;
}
Another way :
class Point
{
public :
Point(double X,double Y)
{
x= X;
y = Y;
}
Private :
double x,y;
}
I want to know which one is better and why?Is there is the use of copy ctor in the first case?
Where each one is preferred?Can some explain with the example?
Rgds,
Softy
Use initializer lists when possible. Although in this particular case it makes no difference, you'll get in the habit.
For POD types, the members don't get initialized twice so performance-wise it's the same thing. non-POD types are initialized before entering the constructor body, so they'll be initialized twice if you don't do it in the initializer list but in the body of the c-tor.
const members and references must be initialized in the initializer list. Again, doesn't apply to your case.
The second version does an assignment to the data members, whereas the first initializes them to the given values. The first version is preferred here. Although it may make little difference in the case of doubles, there is no reason at all to prefer a construction that performs extra operations. If your data members were not doubles, but types that are expensive to construct, you would be paying the penalty of default constructing them, and then assigning a value to them.
Example:
struct ExpensiveToConstruct { .... };
struct Foo {
Foo() {
// here, x has already been default constructed
x = SomeValue; // this is an assignment to the already constructed x.
}
ExpensiveToConstruct x;
};
struct Bar {
Bar : x(SomeValue) {
// only the constructor has been called. No assignemt.
}
ExpensiveToConstruct x;
};
Better to use initialize list in your ctor. It would be more efficient. In your 2nd way, ctor will initialize member data twice, with default value 1st, and then invoke statement in ctor.
and more, for const or reference member, should be initialized by init lists, cannot be initialized in ctor.