PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, October 20, 2022

[FIXED] Why is compiler throwing "expected a type specifier"?

 October 20, 2022     c++, class, datamember, initialization, visual-studio     No comments   

Issue

class A
{
private:
   int a;

public:
   int get_a()
   {
      return a;
   }
   A(int mode)
   {
      a = 0;
   }
   A()
   {
      a = 5;
   }
};

class B
{
public:
   A b(0);   
};

class C
{
   int c;

public:
   C(int mode)
   {
      c = 0;
   }
   C()
   {
      c = 1;
   }
};

int main()
{
   B bb;
   C cc(0);
   //cout << bb.b.get_a();
   system("pause");
   return 0;
}

if im using () brackets on b in class B it gives the error if i switch to {} everything is fine . My question is shouldn't i be allowed to do that since on cc in main it doesn't give any error. And im allowed to use () brackets when initializing objects.


Solution

According to the C++ 20 Standard (11.4 Class members) you may use a brace-or-equal-initializer to initialize a data member of a class

member-declarator:
    ...
    declarator brace-or-equal-initializeropt

So you may use either

class B
{
public:
   A b = 0;   
};

or

class B
{
public:
   A b { 0 };   
};

This allows to avoid an ambiguity with a function declaration.



Answered By - Vlad from Moscow
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing