Asking for help with the two function sum() and print()

1
2
3
4
5
6
7
8
 :\Dev-Cpp\Chapter1\Exercise14.cpp: In member function `void testClass::print() const':
C:\Dev-Cpp\Chapter1\Exercise14.cpp:23: error: passing `const testClass' as `this' argument of `int testClass::sum()' discards qualifiers

C:\Dev-Cpp\Chapter1\Exercise14.cpp: In function `int main()':
C:\Dev-Cpp\Chapter1\Exercise14.cpp:39: error: no matching function for call to `testClass::sum(int, int)'
C:\Dev-Cpp\Chapter1\Exercise14.cpp:18: note: candidates are: int testClass::sum()

Execution terminated

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
#include<iostream>
using namespace std;

class testClass
{
public:
       int sum();
       void print() const;
       testClass();
       //postcondition: x = 0; y = 0;
       testClass(int a, int b);
       //Postcodition: x = a; y = b;
private:
        int x;
        int y;
};
int testClass::sum()
{
    return ( x + y);
}
void testClass::print() const
{
     cout << "sum = " << sum()<<endl;
}
testClass::testClass()
{
          x = 0; 
          y = 0;
}
testClass::testClass(int a, int b)
{
   x = a;
   y = b;
}

int main()
{
    testClass test;
    test.sum(4, 5);
    test.print();
}                           

const member function, such as testClass::print() const , cannot call non-const member function, such as int testClass::sum().

int testClass::sum() should be a const member function i.e. should be int testClass::sum() const



test.sum(4, 5); should be test.sum();
Last edited on
Thanks Repeater!!!
The program works fine now
1
2
C:\Dev-Cpp\exercise14
sum = 9
> C:\Dev-Cpp\
I really hope this isn't the same directory structure that your compiler is installed in.

Topic archived. No new replies allowed.