constructors

I want to add the following to my code. But not sure how to do it.

A default constructor

User defined constructor

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
 #include <iostream>

using namespace std;

void Start_Program();
int Addition(int,int);
int Subtraction(int,int);
int Multiply(int,int);
int Divide(int,int);


int main()
{
    Start_Program();

    return 0;
}
void Start_Program(){
    int a;
    int b;

    std::cout <<"Start Program input 2 numbers" << endl;
    cin >>a;
    cin >>b;
    std::cout <<a<<"+"<<b<<"="<<Addition(a,b)<<endl;
    std::cout <<a<<"-"<<b<<"="<<Subtraction(a,b)<<endl;
    std::cout <<a<<"*"<<b<<"="<<Multiply(a,b)<<endl;
    std::cout <<a<<"/"<<b<<"="<<Divide(a,b)<<endl;

}
int Addition(int a,int b)
{
return(a+b);

}
int Subtraction(int a,int b)
{
return(a-b);

}
int Multiply(int a,int b)
{
return(a*b);

}
int Divide(int a,int b)
{
return(a/b);

}
You must have a class/struct then you can have constructors:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Program {
    int a, b;
public:
    Program(); //default constructor
    Program(int, int); //user defined constructor
    void Start_Program();
    int Addition(int,int);
    int Subtraction(int,int);
    int Multiply(int,int);
    int Divide(int,int);
};

Program::Program() {
    //...
}

Program::Program(int i1, int i2) {
    //...
}

int Program::Addition(int a, int b) {
   //...
}


1
2
3
4
5
6
int main() {
     Program program1; //default constructor
     Program program2 (1, 2); //user defined constructor
     std::cout << program1.Addition(4, 5);
     return 0;
}
I've created a class and have added it to my project.
But im still not sure what to do.
can you please explain how i add
A default constructor
User defined constructor
After ive made a new class.
dleanjeanz already gave you an example of creating a default constructor at line 13. Not sure if you used his example or not. If you did, then you probably want to initialize a and b to zero inside the default constructor.

Likewise, for the user defined constructor (line 17), you want to initialize a and b to i1 and i2 respectively.

If you're not following that example, then post what you have.
Go to this tutorial site: http://www.cplusplus.com/doc/tutorial/classes/
There is part II
Last edited on
seriously, i don't think there's should be classes for a calculator program
CMIIW
seriously, i don't think there's should be classes for a calculator program

Why on Earth not?
Topic archived. No new replies allowed.