The correct way of building an object using a no-arguments constructor is
Circle c2;
Not
Circle c2();
This latter line is a function declaration.
Question
Hi I'm new to C++ and having trouble with the following code:
#include "stdafx.h"
#include <iostream>
using namespace std;
class Shape
{
public:
virtual void area() = 0;
virtual void perimeter() = 0;
virtual void volume() = 0;
};
class Circle : public Shape
{
protected:
int r;
public:
Circle()
{
r = 0;
}
Circle(int num)
{
r = num;
}
void area()
{
double area = (r * r) * (3.14);
cout << "The area of the circle = " << area << endl;
}
void perimeter()
{
double perimeter = 2 * (3.14) * r;
cout << "The circumference of the circle = " << perimeter << endl;
}
void volume()
{
cout << "You are tapping into another dimension. AHHH Error!" << endl;
}
};
class Sphere : public Circle
{
protected:
int r;
public:
Sphere() :Circle()
{
r = 0;
}
Sphere(int num) : Circle(num)
{
r = num;
}
void area()
{
double area = 4 * (3.14) * (r * r);
cout << "The surface area of the sphere = " << area << endl;
}
void perimeter()
{
double perimeter = 2 * (3.14) * r;
cout << "The circumference of the sphere = " << perimeter << endl;
}
void volume()
{
double volume = ((4 / 3) * (3.14) * (r * r * r));
cout << "The volume of the sphere = " << volume << endl;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Shape *ptr;
Circle c1(5);
Circle c2();
Sphere sp1(6);
Sphere sp2();
ptr = &c1;
ptr->perimeter();
ptr->area();
ptr->volume();
ptr = &c2;
ptr->perimeter();
ptr->area();
ptr->volume();
ptr = &sp1;
ptr->perimeter();
ptr->area();
ptr->volume();
ptr = &sp2;
ptr->perimeter();
ptr->area();
ptr->volume();
return 0;
}
The console tells me this:
error C2440: '=' : cannot convert from 'Circle (__cdecl *)(void)' to 'Shape *'
error C2440: '=' : cannot convert from 'Sphere (__cdecl *)(void)' to 'Shape *'
NOTE: I get these ERRORS on the lines containing: "ptr = &c2;" and "ptr = &sp2;"
This is only for the instances that use a constructor with no parameters.
The constructors with parameters work for some reason??
Any help would be nice. Thanks!!!
Solution
The correct way of building an object using a no-arguments constructor is
Circle c2;
Not
Circle c2();
This latter line is a function declaration.
OTHER TIPS
Circle c2();
That does not declare a Circle
; it declares a function.
Just write Circle c2;
.
Same for your Sphere
declaration underneath.
Your hint is that the error message said 'Circle (__cdecl *)(void)'
, which is a function pointer type.