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

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.

Related

Class Inheritance default constructor cannot be referenced [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 4 years ago.
Improve this question
Questions : 33978185 , 32569833 didn't helped me.
By the way, in question 33978185 this error is considered as a bug, but since im using VS2017 i think it should be fixed by now.
Question 40181845 is using structs and i dont understand it quite well...
Question 38469597 says that i should make class B - friend class, is that the case here too?
I tried to search for more solutions but i havent got what i need.
Consinder my level of programming knowledge of object oriented c++ : Advanced> Normal > Begginer.
I am Normal.
I have class A, and class B:
class A
{
protected:
int q;
int w;
public:
A(int);
functionE();
functionR();
};
class B:public A
{
public:
functionT();
};
in main when i want to create a object of class B, I get error:
the default constructor "objectname" cannot be referenced -- its a deleted function.
From my knowledge of object oriented programming, when some members are protected, they can be accessed by the inherited class, and if inheritance is public, it can access public function.
I want my class B to have bonus functionT() and nothing else, but as i said, be able to access protected members of class.
One solution is to actually code functionT() in class A, which removes the need for class B, but I don't want that.
What should i do?
When you're trying to create an object of class B, you get an error as you didn't declare any constructor. B can't have a default constructor, as A doesn't have one either (when you declared A(int) as A constructor, you implicitly deleted the default constructor).
You can either create a default constructor for A, or default it by A() = default
or create a constructor for B, like so
B() : A(0) {}
B(int i) : A(i) {}
By providing the constructor A(int) the default constructor A() gets deleted. However, when creating an instance of class B it must call the constructor of its superclass A. The only way you provide is calling the default constructor, which doesn't exist anymore and thus your code does not compile.
In order for it to compile, you need to tell B how it is supposed to construct A. You can for example add this constructor to B: B(int a) : A(a) {}
Since you have a custom constructor for class A it needs to be called by the constructor of class B.
The generated 'empty' constructor of class B tries to call the 'empty' one of class A, which is no longer available. So you need to write a constructor for B as well.
class B : public A
{
public:
B() : A(0) {}
/* or */
B(int v) : A(v) {}
};

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.

Shared Pointer for parent and child [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I have a problem with the initialization of some classes. Simplified code looks like:
class Base
{
Base(int)
};
class BaseChild : public Base
{
};
class mainWindow
{
boost::shared_ptr<Base> pBase;
void init();
};
void mainWindow::init()
{
this->pBase = boost::shared_ptr<Base>(new Base(12));
this->pBase = boost::shared_ptr<Base>(new BaseChild(12));
}
So the problem is with initialization of BaseChild class which is child from Base class. What am I doing wrong? I thought that parentral class pointer can point on child class.
Generaly my program has to work in such way:
When it starts, there is initialization of parental class (in above example: this->pBase = boost::shared_ptr<Base>(new Base(12));). This already works.
In some case, when some flag change its value, pointer which point on parental class object should be change to point on child class object.
You miss a constructor that takes int in BaseChild. Also constructor in Base is private, which makes it unusable outside Base class.
Try
class Base
{
public:
Base(int);
};
class BaseChild : public Base
{
public:
BaseChild(int);
};

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

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) // <-
{
}

Can a Constructor be Private in C++? [closed]

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
Can a constructor be private in C++? If yes then how can we call it?
class Puma
{
int a = 10;
Puma()
{
cout << a;
}
};
int main()
{
Puma pum;
return o;
}
Can this program run? If not then how can we call Puma() constructor as it is private?
Yes, a constructor can be private. And you can call it with member functions (static or non) or friend functions.
class Puma
{
public:
static Puma create(int a) { return Puma(a); }
private:
int age;
Puma(int a) :age(a) {}
friend Puma createPuma(int a);
};
Puma createPuma(int a) { return Puma(a); }
For possible use cases, see the Factory Pattern, or the Named Constructor Idiom.
Yes. Constructor may be private.
In this case you may create class
Using another (public) constructor
Calling constructor from the same class
Calling constructor from the friend class/function
In your code, the program cannot run since you have defined a constructor and it is private. Therefore, in your current code, there is no way to create objects of the class, making the class useless in a sense.
One way to do is that you can provide public static functions, those static functions call the private constructors to create objects of class.
One minor thing:
return o;
should be
return 0;
Yes a constructor can be private. It is useful when called by a static member function (or a friend), e.g.
class Even {
/// in practice, some more C++ code is probably needed
private:
int x;
Even(int a) : x(a) {};
public:
int get () const { return 2*x; };
static Even* make(int y) { return new Even(y); };
};
the example is not very realistic, but you get the idea. In the using code, do
Even* e = Even::make(3);
Be however aware of the C++ rule of five and do read a good C++ programming book and the documentation of your C++ compiler (e.g. GCC or Clang) and of your debugger (e.g. GDB). You may even want to use the Clang static analyzer.
For examples, download, then look inside the source code of Qt, of FLTK, of RefPerSys, of fish, of GCC or Clang.
Singleton can have a private constructor that will be called from a static method of a class.