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

Thursday, October 20, 2022

[FIXED] When to use which data member initialization in C++

 October 20, 2022     c++, class, data-members, initialization     No comments   

Issue

Considering this program:

#include <iostream>

class C
{
public:
    C(void): a(1)
    { a=2; }
    int a{3};
};

int main(void)
{
    C c{};
    std::cout << c.a; // 2
}

I can see three forms of data member initialization:

  1. using a member initializer list
  2. using the Constructor
  3. using a declaration in the class body

When to use which?


Solution

1: Using a declaration in the class body

You should use this when the member will always be initialized with the same value, and it doesn't make sense to have to explicitly write that for each constructor.

2: Using a member initializer list

The member initializer list is obviously necessary for a member that lacks a default constructor, but aside from that, if you're initializing a member based on the constructor, it makes sense to do it here.

3: Using the constructor body

The constructor body is more useful for logic that can't be performed in a single statement (in the init-list). However, I don't think there is much difference between initializing a POD in the member initializer list or the constructor body.



Answered By - Weak to Enuma Elish
Answer Checked By - Candace Johnson (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