Definition and access identifier of class in c++ - c++

I am a new c++ beginner.I have added private access identifier.Why does it throw this error?Thanks
class test
{
private:
test()
{
};
~test()
{
};
public: void call()
{
cout<<"test"<<endl;
} ;
};
error:
error: 'test::test()' is private|

If a constructor is private, you can't construct (define) an object of the class from outside the class itself (or outside a friend function).
That is, this is not possible:
int main()
{
test my_test_object; // This will attempt to construct the object,
// but since the constructor is private it's not possible
}
This is useful if you want to limit the construction (creation) of object to a factor function.
For example
class test
{
// Defaults to private
test() {}
public:
static test create()
{
return test();
}
};
Then you can use it like
test my_test_object = test::create();
If the destructor is private as well, then the object can't be destructed (which happens when a variables (objects) lifetime ends, for example when the variable goes out of scope at the end of a function).

Related

How do you access member functions of a class object from within a different class object that has been created in it?

class Class1 //Would be object mClass1
{
public:
void Function1()
{
a++;
}
private:
int a = 0;
Class2 mClass2;
}
(Editing in a space here to clarify Class2 is not defined after Class1; they are in separate files.)
class Class2 //Would be object mClass2
{
public:
Function2()
{
Function1(); // Would be from mClass1
}
}
So Class1 creates an instance of a Class2 object, and that Class2 object has a member function that wants to access the "parent" object's member function, without using inheritance.
I don't know what I specifically need to search for to learn about this. Does it have to do with dereferencing a new pointer? Constructor type/initialization? Does it have a terminology? "Nested classes" bring up classes defined inside another class, which is not what this is.
Without inheritance there is no way to get the 'parent class'. So instead you should just pass the function as a parameter, maybe in the constructor of class 2 if you use it multiple times. See for example: https://www.cprogramming.com/tutorial/function-pointers.html
You cannot do this. Class2 is not known yet when you define Class1, so the Class1::mClass2 data member cannot possibly be created. But this problem can be solved by defining Class2 before Class1, and implementing Class2::Function2() outside the class and only after Class1.
As for calling Function1() inside Function2(), Class2 needs to know the object on which to call Function1(). You could use a reference member for that that you initialize in the constructor:
// Forward-declaration of Class1 so that Class2 will be able to define
// references or pointers to Class1.
class Class1;
class Class2
{
public:
// Constructor that requires a reference to our parent object.
explicit Class2(Class1& parent)
: parent_(parent)
{ }
// Just declare the function. We need to implement it later, outside
// this class definition because Class1 is not fully known yet and as
// a result we can't have calls to Function1() because the compiler
// doesn't know that function yet.
void Function2();
private:
// This is just a reference, so it works even if Class1 is not fully
// known yet.
Class1& parent_;
};
class Class1
{
public:
void Function1() { /* ... */ }
private:
int a = 0;
Class2 mClass2{*this}; // Pass ourself as the parent object.
};
// Class1 is fully known now, so we can do calls to Function1().
inline void Class2::Function2()
{
parent_.Function1();
}
This will work, but it has an important implication: it disables the assignment operator of Class2. This is probably what you want in this case, because two copies of Class2 should probably not have the same Class1 parent object.
However, I don't see why you need to do this. It complicates matters for no good reason. Why not simply pass the Class1 object that Function2() should use as a function argument instead? So:
class Class1;
class Class2
{
public:
void Function2(Class1& c1_obj);
};
class Class1
{
public:
void Function1() { /* ... */ }
private:
int a = 0;
Class2 mClass2;
};
inline void Class2::Function2(Class1& c1_obj)
{
c1_obj.Function1();
}
So whenever Class1 needs to call Class2::Function2(), just pass *this to it. It's simpler and doesn't have the drawbacks of holding a reference or pointer to another object.
With canonic classes - no way to do this, because Class2 is incomplete within Class1 and if you declare Class2 inside of Class1 (as a nested class), it wouldn't have access to Class1, because Class1 incomplete!
Looks like an unsolvable paradox? It is unsolvable in OOP land, but can be dodged just like Nikos had shown. But the problem of undefined types in some cases can be resolved in C++ or similar concept-oriented languages by using CRTP - Curiously recurring template.
If it is possible or not in your use-case and how complex it would be depending on what purpose you pursue. Here is an example of a paradoxical CRTP behavior - a member of base class is able to call a member of derived class:
#include <iostream>
template < class T>
class Base {
public:
template <class U>
struct Accessor : public U {
static void evoke_foo( T& obj)
{
return (obj.*(static_cast< void(T::*)() >(&Accessor::foo))) ();
}
};
void evoke( )
{
Accessor<T>::evoke_foo( *static_cast<T*>(this) );
}
};
class Derived : public Base<Derived> {
protected:
void foo() { std::cout << "Foo is called" << std::endl; }
};
int main()
{
Derived a;
a.evoke(); // evoke belongs to base.
}
Now if we'd want to determine return type of foo() automatically here, this would become an insanely complex piece of code. Some problems like that are solved in implementations of standard namesake of evoke method.

Private default constructor specified in class but not implemented in C++ [duplicate]

I have a question about private constructors in C++. If the constructor is private, how can I create an instance of the class?
Should we have a getInstance() method inside the class?
There are a few scenarios for having private constructors:
Restricting object creation for all but friends; in this case all constructors have to be private
class A
{
private:
A () {}
public:
// other accessible methods
friend class B;
};
class B
{
public:
A* Create_A () { return new A; } // creation rights only with `B`
};
Restricting certain type of constructor (i.e. copy constructor, default constructor). e.g. std::fstream doesn't allow copying by such inaccessible constructor
class A
{
public:
A();
A(int);
private:
A(const A&); // C++03: Even `friend`s can't use this
A(const A&) = delete; // C++11: making `private` doesn't matter
};
To have a common delegate constructor, which is not supposed to be exposed to the outer world:
class A
{
private:
int x_;
A (const int x) : x_(x) {} // common delegate; but within limits of `A`
public:
A (const B& b) : A(b.x_) {}
A (const C& c) : A(c.foo()) {}
};
For singleton patterns when the singleton class is not inheritible (if it's inheritible then use a protected constructor)
class Singleton
{
public:
static Singleton& getInstance() {
Singleton object; // lazy initialization or use `new` & null-check
return object;
}
private:
Singleton() {} // make `protected` for further inheritance
Singleton(const Singleton&); // inaccessible
Singleton& operator=(const Singleton&); // inaccessible
};
A private constructor is commonly used with Builder methods, for example in the Named Constructor idiom.
class Point
{
public:
static Point Polar(double, double);
static Point Cartesian(double, double);
private:
Point(double,double);
};
In this (typical) example, the Named Constructor idiom is used to make it explicitly which coordinate system is used to build the Point object.
A private constructor is useful when you want to control the object creation of a class.
Let’s try in code:
#include <iostream>
using namespace std;
class aTestClass
{
aTestClass() ////////// Private constructor of this class
{
cout << "Object created\n";
}
public:
};
int main()
{
aTestClass a;
aTestClass *anObject;
}
The line aTestClass a causes an error because this line is indirectly trying to access the private constructor. Comment out this line and run the program. It runs absolutely fine. Now the question is how to create the object in a such case. Let's write another program.
#include <iostream>
using namespace std;
class aTestClass
{
aTestClass() ////////// Private constructor of this class
{
cout << "Object created\n";
}
public:
aTestClass* getAnObject() ///// A public method create an object of this class and return the address of an object of that class
{
return (new aTestClass);
}
};
int main()
{
//aTestClass a;
aTestClass *anObject = NULL;
anObject = anObject->getAnObject();
}
The output is
Object created
so we have created an object of the class containing a private constructor.
Use this concept to implement a singleton class
Yes, this is commonly used in the Singleton pattern where the object is accessed through a static member function.
If some constructor is private, it means that no one but the class itself (and friends) should be able to create instances of it using that constructor. Therefore, you can provide static methods like getInstance() to create instances of the class or create the instances in some friend class/method.
It depends on why the constructor was made private in the first place (you should ask whoever wrote the class you are editing). Sometimes a constructor may be made private to disallow copy construction (while allowing construction through some other constructor). Other times a constructor may be made private to disallow creating the class except by the class's "friend"s (this is commonly done if the class is a "helper" that should only be used by the class(es) for which the helper class was created). A constructor may also be made private to force the use of a (usually static) creation function.
If you create a private constructor you need to create the object inside the class
#include<iostream>
//factory method
using namespace std;
class Test
{
private:
Test(){
cout<<"Object created"<<endl;
}
public:
static Test* m1(){
Test *t = new Test();
return t;
}
void m2(){
cout<<"m2-Test"<<endl;
}
};
int main(){
Test *t = Test::m1();
t->m2();
return 0;
}
A private constructor in C++ can be used for restricting object creation of a constant structure. And you can define a similar constant in the same scope like enum:
struct MathConst{
static const uint8 ANG_180 = 180;
static const uint8 ANG_90 = 90;
private:
MathConst(); // Restricting object creation
};
Access it like MathConst::ANG_180.

Is there a way to initialize a member object of a class within the constructors code instead of the initializer list?

Consider I want to wrap some library code inside an object. That library needs to be set up and initialized by calling some function inside the constructor of that wrapper class.
The librarie's "objects" then diverge into creating more, different "objects" that the wrapper class wraps in form of yet another wrapper object that should be a plain member of that class.
But as far as I see it, members of classes can only be initialized or created by calling their constructor in the initalizer list of the constructor. The execution of these bits of code preceed the constructor of the actual class that does the initialization of the library and its environment, making it impossible for me to actually initialize that member object as a member and instead force me to initialize it as a pointer to the 2nd wrapper, because its constructor must be called manually within the first constructor's code.
Example:
class A {
public:
A() {
if(!wrapped_library_init()) {
exit(CRITICAL_ERROR);
}
ptr_to_some_library_metadata *a = library_function(); /*Needs to
be called after wrapped_library_init() or needs a pointer to some
wrapped object created inside this constructor */
//initialize b
}
private:
B b; //Wants to be a member but can not
};
class B {
B(ptr_to_some_library_metadata *a);
}
Member objects can only be constructed in the member initializer list. There are a few techniques which can be used to make it possible to initialize an object, though:
Use a helper [lambda] function doing the necessary extra work before return a suitable object. For example:
A()
: B([]{
if (!wrapped_library_init()) {
exit(CRITICAL_ERROR);
}
return library_function();
}()) {
}
You can delay construction by using a union with just the appropriate member. When using this technique the member needs to be explicitly destructed, for example:
class A {
union Bu { B b };
Bu b;
public:
A() {
if (!wrapped_library_init()) {
exit(CRITICAL_ERROR);
}
new(&b.b) B(library_function());
}
~A() {
b.b.~B();
}
// ...
};
I'd personally use the first approach. However, there are cases when using a union to delay construction is helpful.
Initializer lists are there to use another constructor than the default constructor.
But nothing impedes you for creating a custom function that will initialize b:
class A {
public:
A():b(init()) {
}
private:
B b; //Wants to be a member but can not
static B init()
{
if(!wrapped_library_init()) {
exit(CRITICAL_ERROR);
}
ptr_to_some_library_metadata *a = library_function(); /*Needs to
be called after wrapped_library_init() or needs a pointer to some
wrapped object created inside this constructor */
return B(a);
}
};
Wrap your library inside a class:
class LibraryWrapper
{
public:
LibraryWrapper()
{
if(!wrapped_library_init()) {
exit(CRITICAL_ERROR);
}
lib_data.reset(library_function()); /*Needs to
be called after wrapped_library_init() or needs a pointer to some
wrapped object created inside this constructor */
}
//~LibraryWrapper() {/**/}
//LibraryWrapper(const LibraryWrapper&) {/**/} // =delete; ?
//LibraryWrapper& operator=(const LibraryWrapper&) {/**/} // =delete; ?
//private: // and appropriate interface to hide internal
std::unique_ptr<ptr_to_some_library_metadata, CustomDeleter> lib_data;
};
class B {
public:
explicit B(ptr_to_some_library_metadata *a);
// ...
};
And use extra member or inheritance:
class A
{
public:
A() : b(lib.lib_data.get()) {}
private:
LibraryWrapper lib; // placed before B
B b;
};

Difference between passing arguments to the base class constructor in C++

What is the difference in passing arguments to the base class constructor?
Dog::Dog(string input_name, int input_age) : Pet(input_name, input_age) { }
Dog::Dog(string input_name, int input_age) { Pet(input_name, input_age); }
Look the following snippet:
class Cat {
private:
const int m_legs;
public:
Cat() : m_legs{4}
{
}
};
In the snippet above this is the only way you have to initialize a constant because m_legs is initialized before the body of constructor.
Another case is exeptions managment:
class Test {
private:
ICanThrow m_throw;
public:
Cat() try : m_throw{}
{
}
catch(...)
{
// mangage exception
}
};
I usually prefer initialize member before ctor body or when I can initialize members directly in the class declaration:
class Cat {
public:
void meow()
{
}
private:
const int m_legs = 4;
string m_meow{"meow"};
};
If Pet has no default constructor, only 1) will work.
By the time you get into the actual body of the constructor all members and bases have already been constructed. So if a base class has no default constructor you need to tell the compiler which constructor you want it initialised with, and do it before the body of the constructor - this is what the initialiser list is for.
Another reason is if a base or member is const - you can't modify it in the body of the constructor.

When do we need a private constructor in C++?

I have a question about private constructors in C++. If the constructor is private, how can I create an instance of the class?
Should we have a getInstance() method inside the class?
There are a few scenarios for having private constructors:
Restricting object creation for all but friends; in this case all constructors have to be private
class A
{
private:
A () {}
public:
// other accessible methods
friend class B;
};
class B
{
public:
A* Create_A () { return new A; } // creation rights only with `B`
};
Restricting certain type of constructor (i.e. copy constructor, default constructor). e.g. std::fstream doesn't allow copying by such inaccessible constructor
class A
{
public:
A();
A(int);
private:
A(const A&); // C++03: Even `friend`s can't use this
A(const A&) = delete; // C++11: making `private` doesn't matter
};
To have a common delegate constructor, which is not supposed to be exposed to the outer world:
class A
{
private:
int x_;
A (const int x) : x_(x) {} // common delegate; but within limits of `A`
public:
A (const B& b) : A(b.x_) {}
A (const C& c) : A(c.foo()) {}
};
For singleton patterns when the singleton class is not inheritible (if it's inheritible then use a protected constructor)
class Singleton
{
public:
static Singleton& getInstance() {
Singleton object; // lazy initialization or use `new` & null-check
return object;
}
private:
Singleton() {} // make `protected` for further inheritance
Singleton(const Singleton&); // inaccessible
Singleton& operator=(const Singleton&); // inaccessible
};
A private constructor is commonly used with Builder methods, for example in the Named Constructor idiom.
class Point
{
public:
static Point Polar(double, double);
static Point Cartesian(double, double);
private:
Point(double,double);
};
In this (typical) example, the Named Constructor idiom is used to make it explicitly which coordinate system is used to build the Point object.
A private constructor is useful when you want to control the object creation of a class.
Let’s try in code:
#include <iostream>
using namespace std;
class aTestClass
{
aTestClass() ////////// Private constructor of this class
{
cout << "Object created\n";
}
public:
};
int main()
{
aTestClass a;
aTestClass *anObject;
}
The line aTestClass a causes an error because this line is indirectly trying to access the private constructor. Comment out this line and run the program. It runs absolutely fine. Now the question is how to create the object in a such case. Let's write another program.
#include <iostream>
using namespace std;
class aTestClass
{
aTestClass() ////////// Private constructor of this class
{
cout << "Object created\n";
}
public:
aTestClass* getAnObject() ///// A public method create an object of this class and return the address of an object of that class
{
return (new aTestClass);
}
};
int main()
{
//aTestClass a;
aTestClass *anObject = NULL;
anObject = anObject->getAnObject();
}
The output is
Object created
so we have created an object of the class containing a private constructor.
Use this concept to implement a singleton class
Yes, this is commonly used in the Singleton pattern where the object is accessed through a static member function.
If some constructor is private, it means that no one but the class itself (and friends) should be able to create instances of it using that constructor. Therefore, you can provide static methods like getInstance() to create instances of the class or create the instances in some friend class/method.
It depends on why the constructor was made private in the first place (you should ask whoever wrote the class you are editing). Sometimes a constructor may be made private to disallow copy construction (while allowing construction through some other constructor). Other times a constructor may be made private to disallow creating the class except by the class's "friend"s (this is commonly done if the class is a "helper" that should only be used by the class(es) for which the helper class was created). A constructor may also be made private to force the use of a (usually static) creation function.
If you create a private constructor you need to create the object inside the class
#include<iostream>
//factory method
using namespace std;
class Test
{
private:
Test(){
cout<<"Object created"<<endl;
}
public:
static Test* m1(){
Test *t = new Test();
return t;
}
void m2(){
cout<<"m2-Test"<<endl;
}
};
int main(){
Test *t = Test::m1();
t->m2();
return 0;
}
A private constructor in C++ can be used for restricting object creation of a constant structure. And you can define a similar constant in the same scope like enum:
struct MathConst{
static const uint8 ANG_180 = 180;
static const uint8 ANG_90 = 90;
private:
MathConst(); // Restricting object creation
};
Access it like MathConst::ANG_180.