Can a Constructor be Private in C++? [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
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.

Related

Private getters and setters [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 5 years ago.
Improve this question
I am still new to C++ and OOP programming, and I was just wondering about something curious.
I have a class let's name it Foo, with some private members.
My question is: the Foo objects don't "pass data" to other objects during their lifespan. They receive data, do things, and save new data to file. That means, only Foo objects will access Foo private members.
Is it wrong to implement private getters and setters?
Or should I use direct access?
Pseudo code below:
Is this okay?
class foo
{
private:
string a;
string b;
string c;
void setA(string A){this->a=A;}
string getA()const{return this->a;
void setB(string B){this->b=B;}
string getB()const{return this->b;
void setC(string C){this->c=C;}
string getC()const{return this->b;
public:
//many omitted methods//
void Method(); //<-- this method does things and calls private getters and setters to modify private members
}
In main:
{
Foo obj=....;
obj.Method();
}
Or should I:
class foo
{
private:
string a;
string b;
string c;
public:
//many omitted methods//
void Method();
}
void foo::method()
{
string s1;
//initialize s1;
this->a=s1; //operation example
std::cout<<"A equals: "<< this->a;
}
Not sure if I explained my concerns in simple way.
Thank you in advance for your replies and help.
Writing private "getters" and "setters" is pointless, unless you are exploiting polymorphism in some funny way.
Setting up your member variables via a constructor is the best thing to do, and making the members const prevents their unintentional modification.
Avoid "setters" whenever possible regardless of their accessibility as they do little more than circumvent encapsulation.
I'm not the most experienced C++ developer, but from my point of view, using direct access is not a bad practice and it will require less time to write.
On the other hand, having such members in your interface makes it clear that only the Foo objects could read Foo's private members, so both ways are acceptable.
The main point of having getters and setters is controlling access to the class members in a flexible and extensible way. You don't get anything from creating getters and setters if you know they will never be used by external clients of the class, so I would advice to not write them at all.
They will only clutter your source files and make your code harder to read.
By they way, you don't need to use this everytime you want to access a member:
class foo {
private:
string a;
string b;
string c;
public:
//many omitted methods//
void Method();
}
void foo::method() {
string s1;
a=s1;
std::cout<<"A equals: "<< a;
}

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.

Why C++ allows returning a reference to private members [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 9 years ago.
Improve this question
class test {
public:
test(int value = 0): x(value) {}
int& get(){
return x;
}
private:
int x;
};
this will allow client code to mutate the private members
this is legal in C++, but why ?
Is there any situation where you would actually need to break the class encapsulation ?
Make a member as private, means you can not access it directly. But nothing restricts you to access it indirectly via a public member. It depends on you design. You can even do this:
class test {
public:
test() : x(y) {}
int &x;
private:
int y;
};
In your class, assume you want count how many times a member is read/write. So, you can make it private then put a member function which returns a refernce to the variable:
class test {
public:
test(int value = 0): x(value), count(0) {}
int& get(){
count++;
return x;
}
private:
int x;
int count;
};
I hope this example shows how making a member as private and then putting an indirect access to it can be useful.
Ffirst of all let's consider implementing what you describe. It would be very onerous to properly do so. Your example is easy enough. But what if the reference flowed through a number of functions before it reached the function that exposed it? The compiler would have to do exceptionally complex static analysis, beyond the levels of static analysis that are reasonable to expect from compiler writers.
So even if the designers wanted to ban this, it would not have been tractable to do so. Would the designers have wanted to stop this? Very doubtful. Had they done so, how would the [] operator be implemented on a container or a string?
Is there any situation where you would actually need to
break the class encapsulation
As example of the [] operator on containers and strings shows, this feature is in fact used to support encapsulation.
Why? Because C++ mainly tries to let you do whatever you want and not get in your way; it doesn't try very hard to keep you safe. If you want a safe language, use something else. You have something like object-orientation if you want to, but if you want to break out of that, more power to you. With great power comes great responsibility.
It's worth nothing that you don't even need this to break encapsulation; you could simply reinterpret a pointer to "test" as an integer and access the private field this way.

TIP: in C++, having a method where "this" is not used is not good design [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 9 years ago.
Improve this question
Under the hood, a C++ method of a class is like a C function whose first parameter is an instance of the class - or struct.
For example:
void Foo::Do();
would be equivalent to this declaration in C:
void Do(Foo* this);
Hence, using a member m_someMember from within a method is like using this->m_someMember from inside the C function.
After so many years of C/C++ programming experience, I just recently asked myself: What if I call a method from an instance pointer that is NULL???
My guess was: If the method refers to no member at all, when why would it crash?
So I did a quick test (on a Windows platform, with Visual C++ 2008):
class Foo
{
public:
Foo() {}
virtual ~Foo() {}
void Do();
};
void Foo::Do()
{
cout << "Calling 'Do' for " << this << endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
Foo foo;
foo.Do();
Foo* pNullFoo = 0;
pNullFoo->Do();
return 0;
}
Which gives an output like:
Calling 'Do' for 0038FE5C
Calling 'Do' for 00000000
This could be an hassle when doing post-mortem debugging of a crash over an instance pointer that is null. You might think that this method cannot be called if this is invalid.
On the other hand, if the method is declared virtual:
virtual void Foo::Do() { ... }
Then the line:
pNullFoo->Do();
will produce an page fault exception. Why? Because instances of a class with virtual methods have a pointer to the vtable to the child class virtual methods they belong to.
So the first thing the compiler would do is to make pNullFoo to access its vtable member, then bang!
In conclusion, this is better design to have non contextual functions like Do be implemented as procedural routines than methods, unless they are virtual.
Calling a member function on a NULL pointer invokes undefined behavior. Undefined doesn't mean it's going to crash, nor does it mean it's going to do the right thing - it's undefined. Anything could happen.
The only time I've seen this in production code is with Microsoft's CWnd::GetSafeHWND function. But since they wrote the compiler, they can get away with it.
The proper design for member functions that don't need to access any member data is to have them defined as static:
static void Do();
Then call it like:
Foo::Do();
And you don't even need to have an object or a pointer to do that.