1

Please help me to understand the line in main function. What does that means

#include<iostream>

struct ABC
    {
      private:
       int A,
       float B;

      public :
       ABC() {};
       ~ABC(){};

    };

    int main()
    {
       ABC A={};     // What does this statement means?
      return 0;
    }
LPs
  • 16,045
  • 8
  • 30
  • 61
Mukesh
  • 11
  • 1
  • 7

4 Answers4

2

ABC A={} is the same as invoking constructor with no parameter. In your case it is ABC A = ABC();

Lets consider this class (public constructors with 0/1/2 params)

class Hello {
private:
  int x;
  float y;
public:
  Hello() {}
  Hello(int _x) : x(_x) {}
  Hello(int _x, float _y) : x(_x), y(_y) {}
};

Hello h = {} == Hello h = Hello() == just Hello h

Hello h = {1} == Hello h = Hello(1) == Hello h; h.x = 1;

Hello h = {1, 2} == Hello h = Hello(1, 2) == Hello h; h.x = 1; h.y = 2;

John London
  • 1,250
  • 2
  • 14
  • 32
  • if ABC A={} and ABC A both are same then why do we write ABC A ={} ? What is the point of using it? – Mukesh Apr 06 '17 at 09:39
  • `ABC A={1, 2}` is not the same as `ABC A; A.A = 1; A.B = 2;`. If you have no constructor accepting them, it won't compile! it's the same as `ABC A(1,2)` (also applies to {1} version) – pergy Apr 06 '17 at 09:42
  • @pergy You sure? struct S { int x; float y; }; S a = {1, 2}; works for G++ 6.3.0 – John London Apr 06 '17 at 09:44
  • @JohnLondon I was talking about this exact case: private members, only default constructor – pergy Apr 06 '17 at 09:47
  • Ah sorry, didn't see the members are under`private, my bad. Tweak my answer a bit. – John London Apr 06 '17 at 09:48
1
ABC A={};

This is called copy-list-initialization since c++11. In this particular case it's the same as calling: ABC A; or ABC A{} or ABC A() etc. All it does is initializes an object calling a constructor.

nikitablack
  • 4,359
  • 2
  • 35
  • 68
0

In your case ABC A={}; will call default constructor, but... if your class didn't have default constructor (provided by you) = {} initialization would do "a magic" - it would initialize all struct/class members with "zero/default values", i.e.: 0 for numeric types, 0.0 for floating point types, nullptr for pointers... which is much more then default default constructor does.

0

In C++ it has no difference irrespective of {};

But if it was like C style structure like below, then ABC A={}; will reset its members A and B to zero.

struct ABC
{
    int A;
    float B;
};
TuneFanta
  • 157
  • 2
  • 10