Home > database >  possible to using defined name from class outside of class?
possible to using defined name from class outside of class?

Time:03-02

I want to keep the actual struct hidden, but provide a interface name for user.

so my code goes:

class A
{
private:
   struct B{...}; 
public:
 using BPtr = B*;
 B* funct(){...};
} 

my usage would be

A a;
BPtr p = a.funct(); 

CodePudding user response:

The full name is A::BPtr, so this will work:

A::BPtr p = a.funct();

On the other hand, this is pretty pointless, as only the name "B" is private – the class definition isn't.

For example,

class A
{
private:
   struct B{ int x = 1234; } b; 
public:
 using BPtr = B*;
 B* funct(){ return &b; };
};

int main() {
    A a;
    A::BPtr b = a.funct();
    std::cout << b->x << std::endl;
}

outputs "1234", and so does

class A
{
private:
   struct B{ int x = 1234; } b; 
public:
 B funct(){ return b; };
};

int main() {
    A a;
    std::cout << a.funct().x << std::endl;
}

even though A::B b = a.funct(); would not compile (but auto b = a.funct() would).

Lesson: if you hand someone a thing, they can use it - even if they don't know what to call it.

CodePudding user response:

An addition to the answer by @molbdnilo:

Note that even if you don't expose the struct pointer as BPtr, it's not private anymore once you're returning it outside the class.

Here is an example of using the struct outside of the class:

#include <iostream>
#include <type_traits>

class A 
{
private:
    struct B { int num; };
public:
    B* funct() { return new B {}; }
};

int main() 
{
    A a;
    typedef std::remove_reference_t<decltype(*a.funct())> B;

    B b { 3 };
    std::cout << b.num << std::endl;
}
  •  Tags:  
  • c
  • Related