-4

I have two questions regarding classes in C++:

  1. When building a class, do I need a line like this in the code?

    class_name::class_name (float a, float b){ alpha = a; beta = b; }

Or is this line enough to define the inputs as alpha and beta? class_name(float alpha, float beta);

  1. Do I need int main() function in class code?

Thank you!

Karin Din
  • 11
  • 1
  • 5
    Please take a look at [The Definitive C++ Book Guide and List](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). That being said the answer to both of your questions is: _No_. –  Feb 26 '17 at 04:21
  • Hi, What do you mean by saying that the answer to the first quwstion is no? Can I use the line to define inputs to the class as variables? – Karin Din Feb 26 '17 at 04:32
  • `class_name(float alpha, float beta);` will not compile or work. – drescherjm Feb 26 '17 at 04:32
  • 1
    `int main()` has nothing to do with a class. – drescherjm Feb 26 '17 at 04:33
  • 2
    ***Can I use the line to define inputs to the class as variables?*** Certainly not. – drescherjm Feb 26 '17 at 04:36
  • Also you talk about defining a class and at the same time you are showing only a constructor for the class. – drescherjm Feb 26 '17 at 04:37

1 Answers1

0
class_name::class_name (float a, float b){
 alpha = a;
 beta = b;
 }

This is a constructor firstly. Secondly, each constructor is unique to its class. We can do more than simply assigning values in a constructor the way you have asked. The comstructor is a special function, one that initializes variables of a class if required by the coder.

Regarding your question about input parameters, you cannot assign values by simply keeping them the same name. This:

class_name(float alpha, float beta);

Simply defines 2 input parameters in your constructor; it does not assign anything to anything. If your class has a variable named alpha and beta, then it will cause a problem as you have 2 variables with the same name in your function argument. Therefore, this choice is not even valid.

As for your second function, int main() is the function where your program will run. There is only 1 int main() function; you need not declare it anywhere else in your code as it will cause a problem.

As an aside, try finding a good book on the fundamentals of c++, it will assist you in understanding classes in c++ better.

BusyProgrammer
  • 2,783
  • 5
  • 18
  • 31