Object inheritance and encapsulation

I want to define a base class A which allows different type of logging (file stream, console, etc). In the meantime, I want a class B to to be able to call A's print function (i.e. derived class C's print function which defines the logging method). However, I don't want to make A's print function to be public because it will only be called by B. Please could anyone suggest a better approach to re-design this? Many thanks!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class A
{
protected:
    virtual void print(void);
};

class B
{
public:
    B(A * a) : m_pA(a) {}
private:
    void foo() { m_pA->print(); } // fail here
    A * m_pA;
};

class C : public A
{
private:
    virtual void print(void) { /*use different print*/ }
}
Last edited on
Make B a friend?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>

struct B
{
    struct logger ;
    explicit B( logger& lg ) : the_logger(lg) {}

    void foo() const { the_logger.print( "hello from B::foo" ) ; }

    struct logger
    {
      virtual ~logger() {}
      private: virtual void print( const char* ) const = 0 ;
      friend B ;
    };

    private: logger& the_logger ;
};

int main()
{
    struct logger_impl : B::logger
    {
        private: virtual void print( const char* cstr ) const override
        { std::cout << "logger_impl::print: '" << cstr << "'\n" ; }
    };

    logger_impl logger ;
    B b( logger ) ;
    b.foo() ;
}

http://coliru.stacked-crooked.com/a/72062c51a4db96a9
Topic archived. No new replies allowed.