1

As i understand we can initiate an object s of class sample through a statement,

sample s=10;  

Compiler will treat the statement as sample s(10). if there is a one argument constructor with in the class sample , the statement would work but if there is no one argument constructor then compiler will flash an error.

I want to know. can we initiate an object of class sample through a statement,

sample s=10,20;  

this is shown in the following example:

class sample {
 private:
        int a,b;  
public:  
    sample(int i) {
        a=i;  
        b=i;  
    }

    sample(int i, int j) {
        a=i;  
        b=j;  
    }

    void display(){
        cout<<a<<endl<<b;  
    }  
};  

void main(){
        sample s = 10;  
        sample c = 10,20;  
        c.display();  
}  

Would the above program work?

ANjaNA
  • 1,404
  • 2
  • 16
  • 29
Prashant Mishra
  • 167
  • 1
  • 9
  • `sample s=10;` is actually the same as `sample s = sample(10);`, not `sample s(10);` – M.M May 15 '15 at 06:41

2 Answers2

4
sample c = 10,20;

This will not compiled. Note that , here is not operator but a declaration separator and expects something like sample c = 10, d = 20

sample c = (10,20);

, operator will be executed and 10 and 20 will be evaluated respectively with later as result. The statment is equivalent to sample s(20);

Would the above program work?

It will not compile.

sample c = (10,20) will compile and run but would not call the constructor with 2 arguments as you might expect.

can i initiate an object of a class through a statement?

Yes, use sample c(10, 20)

In C++11 onwards, a syntax like sample c = {10, 20} is possible using std::initializer_list as constructor argument.

sample(std::initializer_list<int> l) : a(0), b(0) {
    if(l.size() > 2U) { /* throw */ }
    int i = 0;
    for(int x : l) {
        if(i == 0) { a = x; b = x; }
        else if(i == 1) b = x;
        ++i;
    }
}
...
sample c = {10,20};

Live demo here

Mohit Jain
  • 30,259
  • 8
  • 73
  • 100
  • This syntax works for aggregates (which don't have an initializer_list constructor) – M.M May 15 '15 at 06:40
  • @MattMcNabb Thanks, I missed it completely. Edited the answer. – Mohit Jain May 15 '15 at 07:53
  • `sample` isn't an aggregate because it has user-defined constructors. I meant to say that as well as being possible for initializer_list constructors, it's also possible for aggregate initialization – M.M May 15 '15 at 08:16
  • Thanks. [this](http://stackoverflow.com/questions/4178175/what-are-aggregates-and-pods-and-how-why-are-they-special) was helpful. – Mohit Jain May 15 '15 at 08:30
1

Assuming you are already using C++11, it can be achieved with:

auto c = sample(10,20)
Andrzej Pronobis
  • 33,828
  • 17
  • 76
  • 92