0

I'm trying to declare a new obj and call the constructor of class B, all inside of class A.

I get two errors......

error: expected identifier before numeric constant

and

error: expected ‘,’ or ‘...’ before numeric constant

class A {
   public:             
   class B {

      private:
      int num;

      public:
      B(int in)
      {
          num = in;
      }

   };

   B obj(7);  // here is the problem

};

It seems like this line B obj(7); is giving me the errors.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
steve
  • 1
  • 1
    Try `B obj{7};` or `B obj = 7;` – cigien May 06 '20 at 23:15
  • I tried B obj{7}; it worked for my test code, but when I try to print out num .... obj.printFunc();.... I get error: ‘obj’ does not name a type. what is that doing? – steve May 06 '20 at 23:24
  • See the answer to the linked question, it explains it in some depth. – cigien May 06 '20 at 23:25
  • What would `obj.printFunc();` do? `obj` is of type `B`, which doesn't have a `printFunc` method. Anyway, that should be a separate question. – cigien May 06 '20 at 23:30
  • it's a fictitious accessor that would cout the num data member. sorry that wasn't clear. – steve May 06 '20 at 23:34
  • Write it, make it real, then see what it does. – cigien May 06 '20 at 23:37

2 Answers2

1

Before C++11, it is possible to have only member declarations in the class scope. To initialize them, one has to use the class's constructor(s).

class A {
   public:             
   class B {

      private:
      int num;

      public:
      B(int in)
      {
          num = in;
      }

   };

   A() : obj(7) {}

   B obj;

};

Member initializers became available since C++11:

class A {
   public:             
   class B {

      private:
      int num;

      public:
      B(int in)
      {
          num = in;
      }

   };

   B obj{7}; // or: B obj = 7;

};
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
zaufi
  • 6,811
  • 26
  • 34
1

as @cigien pointed out:

class A {
public:
    class B {

    private:
        int num;

    public:
        B(int in)
        {
            num = in;
        }

    };

    B obj{7};  

    // B obj = 7;  
    // can be written like that as long as the constructor is not "explicit"

};
StackExchange123
  • 1,871
  • 9
  • 24