0

I am trying to utilize wxWidgets in Visual Studio (2017) C++. I created two classes. Namely, cApp.h and cMain.h. Then i tried to create new instance of Cmain in cApp. However, it below error:

Error   C2248   'cMain::cMain': cannot access private member declared in class 'cMain'

When I hover over the .h file in Solution Explorer in Visual Studio it shows it is private. I deleted them and created them manually. However, the same result. How can I change it to public? Thank you very much :)

cApp.h

#pragma once
#include "wx/wx.h"
#include "cMain.h"

class cApp : public wxApp
{
public:
    cApp();
    ~cApp();

private:
    cMain* m_frame1 = nullptr;

public:
    virtual bool OnInit();
};

cApp.cpp

#include "cApp.h"

wxIMPLEMENT_APP(cApp);

bool cApp::OnInit()
{
    m_frame1 = new cMain(); // This is the part that gives error
    m_frame1->Show();

    return true;
}

cMain.h

#include "wx/wx.h"

class cMain : public wxFrame
{
    cMain();
    ~cMain();
};

cMain.cpp

#include "cMain.h"

cMain::cMain() : wxFrame(nullptr, wxID_ANY, "First App")
{

}

cMain::~cMain()
{

}
BHOS
  • 91
  • 7

1 Answers1

0

The compiler is right, cMain is private. In C++, members of a class are private by default, basically because of a protection model. From "The Design and Evolution of C++"(Bjarne Stroustrup):

[...]only the declarations placed in the class declaration (supposedly by its owner) can grant access. By default, all information is private.

Access is granted by declaring a member in the public part of a class declaration , or by specifying a function or a class as a friend.

So basically, the public parts of a class should be explicitly made public, or use the keyword friend.

From "The C++ Programming Language" (Bjarne Stroustrup):

In a class, members are by default private; in a struct, members are by default public (§16.2.4).

Considering that the baseline of C++ was C (where members of a struct are public), it's normal than members of a struct in C++ are public too.

So in order to solve the error, you can explicitly made it public

class cMain
{
    public:
    cMain(){};
    ~cMain(){};
};

or use a struct instead of a class.

struct cMain
{
    cMain(){};
    ~cMain(){};
};

Or specify cMain a friend of cApp.

Regarding inheritance, this post is very helpful: Difference between private, public, and protected inheritance

Jose
  • 3,306
  • 1
  • 17
  • 22