2

I assign the value data member why need to use constructor??

I can not create a class constructor and I assign the value of my variable and my code run without creating a constructor?? so why use constructor

my question is We can directly assign value to any data member. see my code:

#include <iostream>
#include <conio.h>

class calculator {
  public:
    int n1=100;
    char grade='a';

    //  public:

    // calculator()
    // {
    //     grade='a';
    //     n1=100;

    // }

    void display()
    {
          std::cout << "first value:" <<grade<< std::endl;
          std::cout << "second value:" <<n1<< std::endl;
    }

};
int main()
{
    calculator cal;
    cal.display();
    return 0;
}

o/p is:

  • first value:a
  • second value:100

and when

#include <iostream>
#include <conio.h>

class calculator {


    int n1;
    char grade;

  private:

    calculator()
    {
         grade='A';
         n1=100;

    }

    void display()
    {
          std::cout << "first value:" <<grade<< std::endl;
          std::cout << "second value:" <<n1<< std::endl;
    }

};
int main()
{
    calculator cal;
    cal.display();
    return 0;
}

and suddenly i want to access private data members for example(employee salary) then how to access private data??

t.niese
  • 39,256
  • 9
  • 74
  • 101
  • 1
    because you are not supposed to make the attributes public ... At least protected, better is private. Child classes should not access parent's attributes directly, they should not be able to break the parent class internal behavior. https://en.wikipedia.org/wiki/Open%E2%80%93closed_principle Open/Closed principle of SOLID principles. – Pierre Emmanuel Lallemant Sep 01 '19 at 13:23
  • 1
    Please do not tag C++ questions with the C tag. – Eric Postpischil Sep 01 '19 at 13:25
  • There are no constructors in C, please don’t tag languages that don’t relate to the question – Sami Kuhmonen Sep 01 '19 at 13:26
  • 1
    The principle of encapsulation lets you hide the details inside the class methods. – stark Sep 01 '19 at 13:26
  • "We can directly assign value to any data member" - *Only* if they are `public`, which they *usually* should not be. – Jesper Juhl Sep 01 '19 at 13:37
  • 1
    I'd suggest buying and *reading* a couple of books from [The Definitive C++ Book Guide and List](https://stackoverflow.com/q/388242/5910058). – Jesper Juhl Sep 01 '19 at 14:09
  • default initiation like `grade='A'; n1=100;` is nothing you would ever do in the body of the constructor. Use [member initializer lists](https://en.cppreference.com/w/cpp/language/initializer_list) , if the initialization depends on the arguments passed to the constructor, or if you want to overwrite the defaults. Setting the defaults is (since c++11) done using `int n1=100; char grade='a';`, as in your first example. Use the body of the constructor only if there is no other possibility. – t.niese Sep 01 '19 at 15:04
  • The second sample should fail to complie because the constructor is private. Maybe you meant to write `public:` where you wrote `private:` ? – M.M Sep 02 '19 at 01:46
  • @M.M see this link:https://imgur.com/a/P5oPxqY i accessing a private variable using the function. is there any way to use a private variable? – jishan nuran Sep 02 '19 at 03:07
  • @jishannuran in the link you posted, you do use a private variable so I'm not sure what your question is – M.M Sep 02 '19 at 04:20

5 Answers5

3

The job of the constructor is to initialize the object so that it is in a consistent and usable state. That means that it should ensure all members have sane initial values and should establish class invariants.

If you don't use a constructor and instead initialize members by hand every time you create an object, then you are first of all duplicating that work all over the place, and secondly you may forget to initialize something sometimes - which would leave the object in an inconsistent state.

Also, most members should not be public (since that leaves you without any control of how they are accessed/modified) and when they are private, a constructor (or in-class initialization) is the only way to initialize them.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70
  • and suddenly i want to access private data members for example(employee salary) then how to access private data means how to display grade and n1 of my class variable?? can u give one example of private data access?? – jishan nuran Sep 01 '19 at 13:58
  • 1
    @jishannuran "and suddenly i want to access private data members" - Then you add a (`public`) *function* to your class that returns the data you want and *call* it. But now you have control over how the data is calculated and returned (it might be more than just reading a single member). You can also add logging and whatever else you please in that function - you may want to update some *other* value every time something is read, for example. And the internals of the class can be sure that nothing external suddenly modified some state without them noticing. – Jesper Juhl Sep 01 '19 at 14:00
  • thanks for replay still i little bit confused. see my link: https://imgur.com/a/8NbCaj8 how to display 5000 salaries when i declare a private variable?? – jishan nuran Sep 01 '19 at 14:17
  • "a private variable can only access function through." - what? Not sure what you mean. – Jesper Juhl Sep 01 '19 at 14:20
  • only one way to use a private variable using a function?? in this link, i m not able to display salary but i want to display salary but how? imgur.com/a/8NbCaj8 – jishan nuran Sep 01 '19 at 14:25
  • @jishannuran "only one way to use a private variable using a function?" - Of course not. Other members of the class *can* access the private member directly (if they so desire/need). But *external* users cannot. – Jesper Juhl Sep 01 '19 at 14:28
  • can u give one example for external users do not access a private variable?? – jishan nuran Sep 01 '19 at 14:42
  • 3
    @jishannuran - No. I'm not going to write a tutorial or try to teach you the basics of OOP or C++ in general. For that, I suggest you take a look at the [The Definitive C++ Book Guide and List](https://stackoverflow.com/q/388242/5910058). – Jesper Juhl Sep 01 '19 at 14:56
  • "If you don't use a constructor and instead initialize members by hand every time you create an object" - the question indicates that he is comparing the use of NSDMIs with the use of constructors; – M.M Sep 02 '19 at 01:42
0

The purpose of a constructor is to ensure objects are created in a consistent state. This helps prevent using them before they're ready. It's true you can just do this from the caller, but this violates the OOP concept of encapsulation in two ways: first, the caller must know enough about the class's implementation to know how to initialize its internal state properly; second, the caller must have access to that state to initialize it.

Patrick87
  • 27,682
  • 3
  • 38
  • 73
0

Unlike the C programming language, C++ is object oriented. One of the main concepts of object-oriented programming is encapsulation. This concept is about a couple of things. First, it is the idea that the data and methods that work on the data are "bundled" together as a unit (defined in a class in C++). The second idea is that the data or internal representation of the class be hidden to the users of the class as much as possible (this is referred to as information hiding). This allows the implementer of the class to change the internal workings of the class without impacting client code (other than necessitating perhaps a recompilation). Consequently, having attributes of a class (and thus of it objects that are instantiated) that are public is something to be avoided. This implies that client access to an object's internal state is only done indirectly through method calls. Thus, initialization of an object is done similarly via a constructor.

Booboo
  • 38,656
  • 3
  • 37
  • 60
0

You can initialize an object in a consistent state without using a constructor and just initializing the fields themselves. When adding a new field, you'll just as likely forget to add initializations to a constructor as you are in the class itself.

In fact, it's better to initialize the values to some default value before even implementing a constructor.

The actual reasons constructors exist is because you can

a) write logic in them

struct A
{
  int field = -1;

  A()
  {
    if(rand() % 2 == 0)
      field = 10;
  }
};

b) receive the desired values from outside

struct B
{
  int field = -1;

  B(const int field)
  {
    this->field = field;
  }
}

c) overload them to have multiple ways of initializing values

struct C
{
  int field = -1;

  C(const int field)
  {
    this->field = field;
  }

  C()
  {
    std::cout << "Default constructor" << std::endl;

    this->field = 0;
  }
}
0

On the topic of constructors, your first code sample is fine. If the implicitly-generated constructor does the right job (as it does in that sample) then by all means use it.

You might see something like second example in a pedagogical (learning) context where the instructor wants to show what a constructor looks like. Or in old code; the syntax used in your first code sample was not added until C++11.

There are of course other situations where a constructor is necessary, e.g. when the class can take construction arguments, such as std::string x("foo");.

The topic of private vs public is a completely separate issue to the topic of constructors . As mentioned by the other answers you can make data members private if you want your class's code to control every way that they can be modified.

M.M
  • 138,810
  • 21
  • 208
  • 365