简体   繁体   中英

In C++, when no constructor is declared for a class, what will happen if I construct an object with arguments?

I have the struct student and I did not declare a constructor. What will happen if I do the following?

struct student{
    int assns, mt, finalExam;
    float grade(){…}

}
student billy (60, 70, 80);

This answer is written according to the question heading, and not the body, as they seem to be gravely conflicting, hope the OP edits this.

You will encounter a error during compile time.

Code:

#include <iostream>
class test
{
   int tt;
};

int main ()
{ 
   test t1 (34);
}

Compiler Error:

 In function 'int main()': 
  10:17: error: no matching function for call to 'test::test(int)'       10:17: note: candidates are: 
 2:7: note: test::test() 
 2:7: note: candidate expects 0 arguments, 1 provided 
 2:7: note: constexpr test::test(const test&)
 2:7: note: no known conversion for argument 1 from 'int' to 'const test&' 
 2:7: note: constexpr test::test(test&&)  
 2:7: note: no known conversion for argument 1 from 'int' to 'test&&'

This happens as there is no constructor defined which takes a parameter. Without the ctor there is no meaning of class, as you can never initialize its data member, and how can you expect something to be constructed if the construction company itself is absent.

The compiler will throw error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM