0

From the below code snipped, need to access member function of class A::B. Since class B is private unable to create object for it from non-member function. Kindly help me in getting resolve out of this without moving Class B into public

Code below for reference

A.h

#include <iostream>

class A
{
public:
  A();
  void Func();
private:
  class B;
  B *b;
};

A.cpp

#include "A.h"
#include "AB.h"

A::A()
{
    b = new B(this);
}
void A::Func()
{
    b->Func();
}

AB.h

#include "A.h"

class A::B
{
public:
  B(A* a);
  void Func();
private:
  A* ptr;

};

AB.cpp

#include "AB.h"

A::B::B(A* a):ptr(a)
{

}

void A::B::Func()
{
    std::cout<<"Do nothing ";
}
static void call_sample()
{
    A::B* tmp;
    //access member function of class A::B
}

Error below for reference:

In file included from AB.cpp:2:0:
AB.h: In function ‘void call_sample()’:
AB.h:3:10: error: ‘class A::B’ is private
 class A::B
          ^
AB.cpp:15:4: error: within this context
 A::B* tmp;
Nerdy
  • 1,016
  • 2
  • 11
  • 27
  • 1
    Why don't you make class `B` `public`? – Yksisarvinen Mar 31 '21 at 11:55
  • 1
    It looks like `call_sample` is an implementation detail of `A::B`, so it would make sense for it to be a private static member of `A::B`. – aschepler Mar 31 '21 at 11:59
  • 1
    What instance of `A::B` are you intending to access? The class on its own would do you no good. (This looks like an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem).) – molbdnilo Mar 31 '21 at 12:08
  • Sorry for missing a requisite, due to other reasons Class B can't be moved to public – Nerdy Mar 31 '21 at 12:16

1 Answers1

2

B is a nested class from A, and it is private, so, as a definition, it is not accessible from the outside. If you need to use B you can decleare B in the public part of A, and then you can use A::B* type.

0xNIC
  • 135
  • 2
  • 10
  • Sorry for missing a requisite, due to other reasons Class B can't be moved to public – Nerdy Mar 31 '21 at 12:16
  • If you have inserted B as private and then you need to use it as "public", then there is a wrong logic in your program – 0xNIC Mar 31 '21 at 12:45