Strange thing seen in classes

See at the end of this program.
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
//header file
//Complex.h

class Complex{
public:
	Complex();
	Complex(double r);
	Complex(double r, double i);
	Complex(Complex &obj);
	Complex add(Complex c);
	double getReal() const;
	double getImag() const;
	void setReal(double r);
	void setImag(double i);
private:
	double real, imag;
};
// .cpp
#include <iostream>
#include "headerfile.h"
using namespace std;

Complex::Complex(){
	real = imag = 0;
}

Complex::Complex(double r){
	real = r;
	imag = 0;
}

Complex::Complex(double r, double i){
	real = r;
	imag = i;
}

Complex::Complex(Complex &obj){
	real = obj.real;
	imag = obj.imag;
}

Complex Complex::add(Complex c){
	Complex sum;
	sum.real = real + c.real;
	sum.imag = imag + c.imag;
	return sum;
}

double Complex::getReal() const{
	return real;
}
double Complex::getImag() const{
	return imag;
}
void Complex::setReal(double r){
	real = r;
}
void Complex::setImag(double i){
	imag = i;
}
//Main.cpp
#include <iostream>
#include "Complex.h"
using namespace std;

int main(){
	Complex a(1.0,2.0),b(2.0,5.0),c(a.add(b));
	
	cout << b.getImag << endl; // b.getImag gives 1, WHY?
	return 0;
}
//I know b.getImag() should be used. 
Last edited on
there should be () <<< cuz you are calling a function LOL

Right

cout << b.getImag() << endl;

wrong!

cout << b.getImag << endl;
Last edited on
I see that you don't have a header guard, I recommend adding one.
Also, no reason in declaring the whole namespace... Change this:

using namespace std;

to :

1
2
using std::cout;
using std::cin;


Make a habit of only using things in a namespace that you actually use in your program.
Last edited on by Fredbill30
None of you have answered my question. I'm asking from where the 1 is coming in the output when we don't use ()???
I know it's a function and we must use, but without parenthesis it should have given an error rather than giving 1 as output.
closed account (Dy7SLyTq)
is it doing a ruby thing? http://www.ruby-lang.org/en/documentation/quickstart/2/
Topic archived. No new replies allowed.