0

Why does private constructor accessible when defining/initializing static member?

Example code is as follows.

[EDIT]

//CA.h
#pragma once

class CA
{
private:

    static CA m_Instance;

    CA();
    ~CA();
};

//CA.cpp
#include "CA.h"

CA CA::m_Instance;

CA::CA()
{
}

CA::~CA()
{
}

// StaticMemberPrivateConstructor.cpp
#include <iostream>
#include "CA.h"

int main()
{
    std::cout << "Hello World!\n";
}

Above code successfully compiles and runs.

Address of m_Instance

I know the reason why definition of static member variable has to be placed outside of its class.

Why do non-constant static variables need to be initialized outside the class?

C++ static member variable and its initialization

How to initialize private static members in C++?

AFAIK, the example code should give error C2248.

However, the example code does not give error C2248. Why?

My assumption is "Static Member Definition" is considered as public static member function. Therefore, it has permission granted to private constructor.

Kind and elaborate answer will be sincerely appreciated.

YoonSeok OH
  • 647
  • 2
  • 7
  • 15
  • "_My assumption is "Static Member Definition" is considered as public static member function_" - No. It will have the access specifier as declared. You don't have a `static` member function in your code though. – Ted Lyngmo Aug 29 '21 at 06:10
  • I don't get how the private constructor relays to the static member definition. – 273K Aug 29 '21 at 06:11
  • Your code can't even compile, it's syntax is invalid. Even with adding a ; after class definition msvc will give this error (apart from other issues). temp.cpp(15,22): error C2248: 'CA::CA': cannot access private member declared in class 'CA' (So which compiler did you use?) – Pepijn Kramer Aug 29 '21 at 06:21
  • Thanks for the comment Ted. I'm sorry but I don't think I am getting your point. "You don't have a static member function in your code though." I don't have static member function because my question was about "CA CA::m_Instance;", which is called static variable definition, entering private constructor and seems working like static member function, not about static member function. – YoonSeok OH Aug 29 '21 at 08:34
  • Thanks for the comment Pepijin. Sorry about incomplete code. Edited code example. What you've said didn't occur, and that's what my question is. There's no error C2248. I'm using Visual Studio 2019, _MSV_VER 1929, ISO C++ 14 Standard. – YoonSeok OH Aug 29 '21 at 08:53
  • in `CA CA::m_Instance;`, you are "in" `CA`'s scope. – Jarod42 Aug 29 '21 at 09:14
  • Thanks for the comment Jarod42. Would you mind if I ask for elaboration? The reason why error C2248 is not occurring is understandable if CA CA::m_Instance; is in CA's scope. But I'd want to know a little bit more detail. Rule, document or such. – YoonSeok OH Aug 29 '21 at 10:04

0 Answers0