How to access a private constructor in a separate class?

I am writing a library in C ++. I have two classes in my library, A and B I want to hide the A() constructor from any code that references my library. I also want class B be able to call constructor A() .

I come from C # background and remember little of my C ++. In C #, I simply declare the A() constructor as internal . I read that the closest way to do this in C ++ is through a combination of friend declarations and forward-declarations. How can I do it? Below are my three files:

hijras:

 #pragma once class A { private: A(); }; 

Bh

 #pragma once class A; class B { public: A createA(); }; 

B.cpp:

 #include "Ah" #include "Bh" AB::createA() { A result; //cannot access private member declare in class 'A' return result; } 

I tried adding this to Ah:

 public: friend A createA(); 

Instead, I tried adding this to Ah with the appropriate declaration:

 public: friend AB::createA(); 

Instead, I tried to add extern class B; in Ah and made B a class as follows:

 public: friend class B; 

I'm at a loss.

I think it might be easier if the function B::createA() returns a pointer to object A , and not object A , but this will not be done in my case. I emulate a private API, and an API call returns an A object, not a pointer.

+6
source share
4 answers

You probably just need to abandon extern from your third attempt to turn it into a proper forward declaration. Try:

hijras:

 #pragma once class B; class A { friend class B; private: A(); }; 
+3
source

If absolutely necessary, you must have A (or have a factory that creates A ). If you really want B to do this:

 class B; // foward declared class A { private: A() {} friend class B; }; class B { public: A CreateA() { A a; return a; } }; int main() { B b; A a = b.CreateA(); return 0; } 

Note You must send announcement B before declaring his friend to A

If you want only the function as a friend:

 class A; class B { public: A CreateA(); }; class A { private: A() {} friend class AB::CreateA(); }; AB::CreateA() { A a; return a; } int main() { B b; A a = b.CreateA(); return 0; } 
+1
source

You do not need the external keyword. Make it simple:

 // In Ah class B; // Forward declaration class A { friend class B; // Make all the class B friend A(); }; // In Bh class B { public: A createA() {} }; 

Live example .

+1
source

You can make B a friend of A:

 class A { private: A(); friend class B; }; 
0
source

Source: https://habr.com/ru/post/953510/


All Articles