Reputation: 1917
I am practicing class declaration/implementation/passing object by reference. Here is my code for my main class, header file, and other class:
//Header file (Circle2.h)
#ifndef CIRCLE_H
#define CIRCLE_H
class Circle{
private:
double radius;
public:
Circle();
Circle(double newRadius);
double getArea() const;
double getRadius() const;
void setRadius(double newRadius);
};
#endif
//Main class (PassObjectByReference.cpp)
#include <iostream>
#include "Circle2.h"
using namespace std;
void printCircle(const Circle &c){
cout << "The area of the circle of " << c.getRadius() << " is " << c.getArea() << endl;
}
int main(){
Circle myCircle(5.0);
printCircle(&myCircle);
return 0;
}
//Other class (Circle2.cpp)
#include "Circle2.h"
Circle::Circle(){
radius = 1;
}
Circle::Circle(double newRadius){
radius = (newRadius >= 0) ? newRadius : 0;
}
double Circle::getRadius() const{
return radius;
}
double Circle::getArea() const{
return radius * radius * 3.14159;
}
void Circle::setRadius(double newRadius){
radius = (newRadius >= 0) ? newRadius : 0;
}
When I try to compile, I get these two errors:
PassObjectByReference.cpp: In function ‘int main()’: PassObjectByReference.cpp:11: error: invalid initialization of reference of type ‘const Circle&’ from expression of type ‘Circle*’ PassObjectByReference.cpp:5: error: in passing argument 1 of ‘void printCircle(const Circle&)’
I can't find the error. Any help would be greatly appreciated. Thank you!
Upvotes: 1
Views: 493
Reputation: 63501
Drop the &
- that's turning it into a pointer, which is not what you want. You should just write:
printCircle( myCircle );
Upvotes: 2
Reputation: 1284
int main(){
Circle myCircle(5.0);
printCircle(&myCircle); // You are passing a pointer.
return 0;
}
The correct statement is:
printCircle(myCircle);
Upvotes: 8