How to initialize inner class that has a c-tor with parameters

S. Beniashvili 20 Reputation points
2024-06-18T12:50:32.0766667+00:00

Hi to all,

I'm trying to write a simple code and it won't compile!

Any ideas?

#include <stdio.h>

class RegClass {

public:

RegClass(int param) { printf("c-tor (%d)\r\n",  param); }

};

class Test {

public:

int a;

RegClass Reg(5);

};

int main() {

Test t;

t.a = 5;

return 0;

}

C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,608 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 114K Reputation points
    2024-06-18T12:58:38.1633333+00:00

    Try to use “{ }”: RegClass Reg{ 5 };

    Or consider the classic approach:

    class Test
    {
    public:
        int a;
        RegClass Reg;
    
        Test( ) : a( 0 ), Reg( 5 )
        {
    
        }
    };
    

0 additional answers

Sort by: Most helpful