c++ does virtual function always got to be a const? - c++

I just wonder if all virtual function has got to be a const?
I'm having some issue with them as the area always return 0 for my square when ever i wanna print them out. would appreciate if someone could enlighten me.
shapetwod.h
class ShapeTwoD
{
protected:
string name, warpSpace;
bool containsWarpSpace;
public:
//constructor
ShapeTwoD();
ShapeTwoD(string, bool);
//accessors/set function
void setName(string);
//mutator/get function
string getName();
//methods
virtual double computeArea();
virtual void view();
};
shapetwod.cpp
ShapeTwoD::ShapeTwoD()
{
string name = "";
}
ShapeTwoD::ShapeTwoD(string ShapeName)
{
name = ShapeName;
}
void ShapeTwoD::setName(string shapeName)
{
name=shapeName;
}
string ShapeTwoD::getName()
{
return name;
}
double ShapeTwoD::computeArea()
{
return 0;
}
void ShapeTwoD::view()
{
cout << "Area is: " << endl;
}
square.h
class Square:public ShapeTwoD
{
private:
int xVal,yVal;
int length, breath;
double area;
public:
Square();
Square(string, int, int, double);
//acessor method
//int getSquareDetails();
int getxCord();
int getyCord();
double getArea();
virtual double computeArea();
void view();
int xvalue[4];
int yvalue[4];
};
square.cpp
Square::Square()
{
xVal = 0;
yVal = 0;
area = 0;
}
Square::Square(string ShapeName, bool warpspace, int xval, int yval, double areas):ShapeTwoD(ShapeName, warpspace)
{
xVal = xval;
yVal = yval;
area = areas;
}
void Square::setSquareCord()
{
for (int i=0; i<4; i++)
{
cout << "Please enter x-ordinate of pt " << i+1 << ": ";
cin >> xVal;
xvalue[i] = xVal;
cout << endl;
cout << "Please enter y-ordinate of pt " << i+1 << ": ";
cin >> yVal;
yvalue[i] = yVal;
cout << endl;
}
}
double Square::computeArea()
{
int xmax = xvalue[1];
int xmin = xvalue[1];
int ymax = yvalue[1];
int ymin = yvalue[1];
for(int i=0; i<4; i++)
{
if(xvalue[i]>xmax)
{
xmax = xvalue[i];
}
else if(xvalue[i]<xmin)
{
xmin = xvalue[i];
}
}
for(int i=0; i<4; i++)
{
if(yvalue[i]>ymax)
{
ymax = yvalue[i];
}
else if(yvalue[i]<ymin)
{
ymin = yvalue[i];
}
}
length = xmax - xmin;
breath = ymax - ymin;
area = length * breath;
return (area);
}
int Square::getxCord()
{
return xVal;
}
int Square::getyCord()
{
return yVal;
}
double Square::getArea()
{
return area;
}
void Square::view()
{
cout << "Name: " << getName() << endl;
cout << "Area is: " << area << endl;
}
Sorry but I don't really know how to phase my question. i'm actually using Polymorphism &
Virtual Functions here and my computeArea and view function are virtual.
so in my square.cpp under the "view" function the programme would always return me 0 and i'm not sure why is this so..
this is how i call the view function. not sure if it's helping here..
void Shape2DLink::InputSensor()
{
string shape,type;
cout<<endl<<"\n"<<"[ Input sensor data ]"<<endl;
cout << "Please enter name of shape: " << endl;
cin >> shape;
shape2D.setName(shape);
cout << "Please enter special type : " << endl;
cin >> type;
shape2D.setWarpSpace(type);
if(shape == "Square")
{
square.setSquareCord();
square.computeArea();
square.isPointOnShape();
square.isPointInShape();
Square *mySquare = new Square;
shapeobject.push_back(mySquare);
//shapeobject.push_back( new Square );
}
}
void Shape2DLink::Display()
{
vector<ShapeTwoD*>::iterator vectorIt = shapeobject.begin();
while(vectorIt != shapeobject.end())
{
(*vectorIt)->view();
vectorIt++;
}
}

I just wonder if all virtual function has got to be a const?
No.
I'm having some issue with them as the area always return 0 for my
square when ever i wanna print them out.
Hmm, ok, let's take a look.
double ShapeTwoD::computeArea()
{
return 0;
}
Yup, uh-huh.
I've got my Magic Monkey Hat on, and I predict that the problem you're having is caused by Object Slicing. Consider:
void foo (Shape2D shape)
{
cout << shape.compute_area() << "\n"
}
int main()
{
Square sq;
foo (sq);
}
Since foo above takes a Shape2D by-value, all the Squareness of whatever is passed to it is sliced away, leaving only a Shape2D. Of course since Shape2D::compute_area just returns 0, that's what is computed.
To fix this particular problem, don't copy the object or take it by-value, but take it by-reference instead:
void foo (Shape2D& shape)
{
cout << shape.compute_area() << "\n"
}
Now the object isn't sliced.
Look for similar problems in the code you haven't shown us.

No a virtual method may or may not be const. Your problem is somewhere else, but not in the code you have included.

Related

How I get center of points?

Problem: Create a vector consisting of point objects in a two-dimensional plane, calculate the average of the x and y coordinates of the point objects, and write a program that outputs the center of the points.
#include <iostream>
#include <string>
#include <iomanip>
#include <vector>
using namespace std;
class Point
{
public:
Point(std::string pname = NULL, int px = 0, int py = 0)
{
setName(pname); setX(px); setY(py);
}
std::string getName() { return name; }
int getX() { return x; }
int getY() { return y; }
void setName(std::string pname) { name = pname; }
void setX(int px) { x = px; }
void setY(int py) { y = py; }
private:
std::string name;
int x;
int y;
};
int main()
{
int a;
int counter = 0;
cout << "number of points" << endl;
cin >> a;
vector<Point> v1(a);
while (counter < a)
{
Point p1;
string tmp;
int tmp_x;
int tmp_y;
cout << "name of point" << endl;
cin >> tmp;
p1.setName(tmp);
cout << "position of point" << endl;
cin >> tmp_x >> tmp_y;
p1.setX(tmp_x);
p1.setY(tmp_y);
v1.push_back(p1);
cout << p1.getName() <<p1.getX() << p1.getY() << endl;
}
return 0;
}
this is an example of what I want (inline is keyboard input)
Number of points: 2
Name of point: p1
position of a point: 10 20
p1 (10, 20)
Name of point: p2
position of a point: 40 50
p2 (40, 50)
centor of points :(25.0, 35.0)
How should I approach averaging?
You don't need all of those #includes.
Pay attention to NULL in class constructor.
Loop continuation condition: a--. Variable counter is redundant.
Vector is dynamic data structure. You don't need to declare its size explicitly, in this exercise. Member-function push_back will do dirty work for you.
One more extra variable p1. Try:
v1.push_back( { tmp, tmp_x, tmp_y } );
Finally...
double // if precision is necessary
total_x{}, total_y{};
for ( auto& point : v1 ) {
total_x += point.getX();
total_y += point.getY();
}
std::cout << "Average X: " << total_x / v1.size()
<< "\nAverage Y: " << total_y / v1.size();
return EXIT_SUCCESS;

it says i have errors but there are no errors [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 9 months ago.
Improve this question
I have tried to run the program with more than one inheritance i got many errors
For this program ,but when i use it for Source File, it will looks good
I don't know why but I think because i update my version or does make any sense
please help me with my project
int main
#include"Shapes.h"
#include"Cylinder.h"
#include"Sphere.h"
#include"Triangle.h"
#include"Square.h"
#define MAX_SHAPES 100
int main() {
ofstream myfile;
myfile.open("Shapes.dat");
Shape* shapes[MAX_SHAPES];
int currentShapes = 0;
int n = 0;
cout << "Select any Number to calculate : \n";
cout << "1. Square\n";
cout << "2. Triangle\n";
cout << "3. Sphere\n";
cout << "4. Cylinder\n";
cout << "Enter your choice: ";
cin >> n;
cin.ignore();
if (n == 1) {
Square* obj2 = new Square();
obj2->readData();
shapes[currentShapes] = obj2;
}
if (n == 2) {
Triangle* obj3 = new Triangle();
obj3->readData();
shapes[currentShapes] = obj3;
}
if (n == 3) {
Sphere* obj5 = new Sphere();
obj5->readData();
shapes[currentShapes] = obj5;
}
if (n == 4) {
Cylinder* obj7 = new Cylinder();
obj7->readData();
obj7->computeSurfaceArea();
obj7->computeVolume();
obj7->print();
obj7->printToFile();
shapes[currentShapes] = obj7;
}
return 0;
}
shape.h
class Shape {
private:
string color, name;
public:
// default constructor
Shape()
{
color = 1.0;
name = "";
cout << "Base Class is Shape for this element . \n";
}
// parameterized constructor
Shape(string color, string name) {
this->color = color;
this->name = name;
}
// read data
void readData() {
cout << "Enter color: ";
getline(cin, color);
cout << "Enter name: ";
getline(cin, name);
}
virtual void print() = 0;
virtual void printToFile() = 0;
virtual void readFromFile(ifstream& input) = 0;
};
shape2d.h
class Shape2D : public Shape {
public:
double area;
double perimeter;
Shape2D() :Shape()
{
cout << "Parent Class is Shape2D for this element .\n";
}
// parameterized constructor
Shape2D(string color, string name) :Shape(color, name) {
}
// read data
void readData() {
Shape::readData();
}
virtual void computeArea() = 0;
virtual void computePerimeter() = 0;
virtual void print() = 0;
virtual void printToFile() = 0;
virtual void readFromFile(ifstream& input) = 0;
};
Shape3d
class Shape3D : public Shape {
public:
double surfaceArea;
double volume;
Shape3D() :Shape()
{
surfaceArea = 1.0;
volume = 1.0;
cout << "Parent Class is Shape3D for this element .\n";
}
// parameterized constructor
Shape3D(string color, string name) :Shape(color, name) {
}
void readData() {
Shape::readData();
}
virtual void computeSurfaceArea() = 0;
virtual void computeVolume() = 0;
virtual void print() = 0;
virtual void printToFile() = 0;
virtual void readFromFile(ifstream& input) = 0;
};
Square.h
class Square : public Shape2D {
private:
double side;
public:
Square() :Shape2D()
{
side = 1.0;
cout << "Calculating square area and perimeter \n";
}
// parameterized constructor
Square(string color, string name, double side) :Shape2D(color, name) {
this->side = side;
}
void readData() {
Shape2D::readData();
cout << "Square Side: ";
cin >> side;
cin.ignore();
computeArea();
computePerimeter();
}
void computeArea()
{
area = side * side;
}
void computePerimeter() {
perimeter = 4 * side;
}
void print(string x, double y)
{
cout << x << " of Square = " << y << "\n";
}
void print() {
print("Area: ", area);
print("Perimeter", perimeter);
}
void printToFile(string x, double y)
{
ofstream ofs;
ofs.open("shapes.dat", ios_base::app);
if (!ofs) {
cout << "Error opening file" << endl;
}
cout << "Shapes.dat file updated .";
ofs << x << " of Square = " << y << "\n";
ofs.close();
}
void printToFile() {
printToFile("Area: ", area);
printToFile("Perimeter", perimeter);
}
void readFromFile(ifstream& input)
{
string data = "";
while (std::getline(input, data))
{
std::cout << data << endl;
}
}
};
Triangle.h
class Triangle : public Shape2D {
private:
double base;
double height;
public:
Triangle() :Shape2D()
{
cout << "This is a Triangle\n";
}
// parameterized constructor
Triangle(string color, string name, double base, double height) :Shape2D(color, name) {
this->base = base;
this->height = height;
}
void readData() {
Shape2D::readData();
cout << "Triangle Base: ";
cin >> base;
cout << "Triangle Height: ";
cin >> height;
cin.ignore();
computeArea();
computePerimeter();
}
void computeArea() {
area = (height * base) / 2;
}
void computePerimeter() {
perimeter = 2 * height + base;
}
void print(string x, double y)
{
cout << x << " of Triangle = " << y << "\n";
}
void print() {
print("Area: ", area);
print("Perimeter: ", perimeter);
}
void printToFile(string x, double y)
{
ofstream ofs;
ofs.open("shapes.dat", ios_base::app);
if (!ofs) {
cout << "Error opening file" << endl;
}
cout << "Shapes.dat file updated .";
ofs << x << " of Triangle = " << y << "\n";
ofs.close();
}
void printToFile() {
printToFile("Area: ", area);
printToFile("Perimeter", perimeter);
}
void readFromFile(ifstream& input)
{
string data = "";
while (std::getline(input, data))
{
std::cout << data << endl;
}
}
};
Sphere.h
class Sphere : public Shape3D {
private:
double radius;
public:
Sphere() :Shape3D()
{
radius = 1.0;
cout << "This is a Sphere\n";
}
// parameterized constructor
Sphere(string color, string name, double side) :Shape3D(color, name) {
this->radius = radius;
}
void readData() {
Shape3D::readData();
cout << "Sphere Radius: ";
cin >> radius;
cin.ignore();
computeSurfaceArea();
computeVolume();
}
void computeSurfaceArea() {
surfaceArea = 4 * 3.14 * radius * radius;
}
void computeVolume() {
volume = (4 / 3) * (3.14 * radius * radius * radius);
}
void print(string x, double y)
{
cout << x << " of Sphere = " << y << "\n";
}
void print() {
print("Surface Area: ", surfaceArea);
print("Volume: ", volume);
}
void printToFile(string x, double y)
{
ofstream ofs;
ofs.open("shapes.dat", ios_base::app);
if (!ofs) {
cout << "Error opening file" << endl;
}
cout << "Shapes.dat file updated .";
ofs << x << " of Sphere = " << y << "\n";
ofs.close();
}
void printToFile() {
printToFile("Surface Area: ", surfaceArea);
printToFile("Volume", volume);
}
void readFromFile(ifstream& input)
{
string data = "";
while (std::getline(input, data))
{
std::cout << data << endl;
}
}
};
Cylinder .h
class Cylinder : public Shape3D {
private:
double radius;
double height;
public:
Cylinder() :Shape3D()
{
radius = 1.0;
height = 1.0;
cout << "This is a Cylinder\n";
}
// parameterized constructor
Cylinder(string color, string name, double radius, double height) :Shape3D(color, name) {
this->radius = radius;
this->height = height;
}
void readData() {
Shape3D::readData();
cout << "Cylinder Radius: ";
cin >> radius;
cout << "Cylinder Height: ";
cin >> height;
cin.ignore();
//computeSurfaceArea();
//computeVolume();
}
void computeSurfaceArea() {
surfaceArea = (2 * 3.14 * radius) * (radius + height);
}
void computeVolume() {
volume = 3.14 * radius * radius * height;
}
void print(string x, double y)
{
cout << x << " of Cylinder = " << y << "\n";
}
void print() {
print("Surface Area: ", surfaceArea);
print("Volume: ", volume);
}
void printToFile(string x, double y)
{
ofstream ofs;
ofs.open("shapes.dat", ios_base::app);
if (!ofs) {
cout << "Error opening file" << endl;
}
cout << "Shapes.dat file updated .";
ofs << x << " of Cylinder = " << y << "\n";
ofs.close();
}
void printToFile() {
printToFile("Surface Area: ", surfaceArea);
printToFile("Volume", volume);
}
void readFromFile(ifstream& input)
{
string data = "";
while (std::getline(input, data))
{
std::cout << data << endl;
}
}
};
In shape2d.h and shape3d.h with have to add
#include "shape.h"
In square.h and triangle.h with have to add
#include "shape2d.h"
In sphere.h and cylinder.h you have to add
#include "shape3d.h"
And to avoid multiple inclusions add at the beginning of each .h file
#pragma once
or if your compiler doesn't support it enclose the hole code inside any .h in something like
#ifndef YOUR_H_FILE_NAME_H
#define YOUR_H_FILE_NAME_H
// ... your .h code here
#endif
Further in main.cpp you include shapes.h which doesn't exist but you can remove it because you already include all the specilized .h file

Cannot instantiate abstract class, but double checked overriding of virtual functions

I'm doing self-study C++. I tried a program from the book, that would normally allocate a few objects of two derived classes dynamically using an array of pointers. I'm however preparing for an assignment where I'm not allowed to use pointers, so I made an alternative version without pointers.
The only error it gives me is C2259 "cannot instantiate abstract class", but I'm pretty sure I have overriden all the virtual functions.
Here is the header:
#ifndef ACCTBAC_H_
#define ACCTBAC_H_
#include <iostream>
#include <string>
// Abstract Base Class
class AcctABC
{
private:
std::string fullName;
long acctNum;
double balance;
protected:
struct Formatting
{
std::ios_base::fmtflags flag;
std::streamsize pr;
};
const std::string& FullName() const { return fullName; }
long AcctNum() const { return acctNum; }
Formatting SetFormat() const;
void Restore(Formatting& f) const;
public:
AcctABC(const std::string& s = "Nullbody", long an = -1, double bal = 0.0);
void Deposit(double amt);
virtual void Withdraw(double amt) = 0; // pure virtual function
double Balance() const { return balance; };
virtual void ViewAcct() const = 0; // pure virtual function
virtual ~AcctABC() {}
};
// Brass Account Class
class Brass : public AcctABC
{
public:
Brass(const std::string& s = "Nullbody", long an = -1, double bal = 0.0) : AcctABC(s, an, bal) {}
virtual void Withdraw(double amt);
virtual void ViewAcct() const;
virtual ~Brass() {}
};
// Brass Plus Account Class
class BrassPlus : public AcctABC
{
private:
double maxLoan;
double rate;
double owesBank;
public:
BrassPlus(const std::string& s = "Nullbody", long an = -1, double bal = 0.0, double ml = 500, double r = 0.10);
BrassPlus(const Brass& ba, double ml = 500, double r = 0.1);
virtual void ViewAcct() const;
virtual void Withdraw(double amt);
void ResetMax(double m) { maxLoan = m; }
void ResetRate(double r) { rate = r; }
void ResetOwes() { owesBank = 0; }
};
#endif
the class functions:
// acctabc.cpp -- bank account class methods
#include <iostream>
#include "acctabc.h"
using std::cout;
using std::ios_base;
using std::string;
// Abstract Base Class
AcctABC::AcctABC(const string& s, long an, double bal)
{
fullName = s;
acctNum = an;
balance = bal;
}
void AcctABC::Deposit(double amt)
{
if (amt < 0)
cout << "Negative deposit not allowed; "
<< "deposit is cancelled.\n";
else
balance += amt;
}
void AcctABC::Withdraw(double amt)
{
balance -= amt;
}
// protected methods for formatting
AcctABC::Formatting AcctABC::SetFormat() const
{
// set up ###.## format
Formatting f;
f.flag = cout.setf(ios_base::fixed, ios_base::floatfield);
f.pr = cout.precision(2);
return f;
}
void AcctABC::Restore(Formatting& f) const
{
cout.setf(f.flag, ios_base::floatfield);
cout.precision(f.pr);
}
// Brass methods
void Brass::Withdraw(double amt)
{
if (amt < 0)
cout << "Withdrawal amount must be positive; "
<< "withdrawal cancelled.\n";
else if (amt <= Balance())
AcctABC::Withdraw(amt);
else
cout << "Withdrawal amount of $" << amt
<< " exceeds your balance.\n"
<< "Withdrawal cancelled.\n";
}
void Brass::ViewAcct() const
{
Formatting f = SetFormat();
cout << "Brass Client: " << FullName() << "\n";
cout << "Account Number: " << AcctNum() << "\n";
cout << "Balance: $" << Balance() << "\n";
Restore(f);
}
// BrassPlus methods
BrassPlus::BrassPlus(const string& s, long an, double bal, double ml, double r) : AcctABC(s, an, bal)
{
maxLoan = ml;
owesBank = 0.0;
rate = r;
}
void BrassPlus::ViewAcct() const
{
Formatting f = SetFormat();
cout << "BrassPlus Client: " << FullName() << "\n";
cout << "Account Number: " << AcctNum() << "\n";
cout << "Balance: $" << Balance() << "\n";
cout << "Maximum loan: $" << maxLoan << "\n";
cout << "Owed to bank: $" << owesBank << "\n";
cout.precision(3);
cout << "Loan Rate: " << 100 * rate << "%\n";
Restore(f);
}
void BrassPlus::Withdraw(double amt)
{
Formatting f = SetFormat();
double bal = Balance();
if (amt <= bal)
AcctABC::Withdraw(amt);
else if (amt <= bal + maxLoan - owesBank)
{
double advance = amt - bal;
owesBank += advance * (1.0 + rate);
cout << "Bank Advance: $" << advance << "\n";
cout << "Finance charge: $" << advance * rate << "\n";
Deposit(advance);
AcctABC::Withdraw(amt);
}
else
cout << "Credit limit exceeded. Transaction cancelled.\n";
Restore(f);
}
and the main program:
// usebrass3.cpp -- polymorphic example using an abstract base class
#include <iostream>
#include <string>
#include "acctabc.h"
#include <vector>
const int CLIENTS = 4;
int main()
{
using std::cin;
using std::cout;
using std::vector;
using std::string;
vector<AcctABC> accounts(CLIENTS);
string temp;
long tempnum;
double tempbal;
char kind;
for (int i = 0; i < CLIENTS; i++)
{
cout << "Enter client's name: ";
getline(cin, temp);
cout << "Enter client's account number: ";
cin >> tempnum;
cout << "Enter opening balance: $";
cin >> tempbal;
cout << "Enter 1 for Brass Account: ";
while (cin >> kind && (kind != '1' && kind != '2'))
cout << "Enter either 1 or 2: ";
if (kind == 1)
accounts.push_back(Brass(temp, tempnum, tempbal));
else
{
double tmax, trate;
cout << "Enter the overdraft limit: $";
cin >> tmax;
cout << "Enter the interest rate "
<< "as a decimal fraction: ";
cin >> trate;
accounts.push_back(BrassPlus(temp, tempnum, tempbal, tmax, trate));
}
while (cin.get() != '\n')
continue;
}
cout << "\n";
for (int i = 0; i < CLIENTS; i++)
{
accounts[i].ViewAcct();
cout << "\n";
}
cout << "Done.\n";
return 0;
}
Here:
vector<AcctABC> accounts(CLIENTS);
you are trying to create a vector of AcctABC with CLIENTS default constructed AcctABC elements. But you cannot have AcctABC elements when the class is abstract. You also cannot have Brass elements in a vector of AcctABCs. You need pointers when you want to store a polymorphic type in a vector.
You cannot do this
vector<AcctABC> accounts(CLIENTS);
because it will make CLIENTS number of default constructed abstract base classes. You will also lose polymorphism and induce object slicing. Instead
vector<std::unique_ptr<AcctABC>> accounts;
then for example
accounts.push_back(std::make_unique<Brass>(temp, tempnum, tempbal));

cout/cin does not name a type error

Whats wrong with this code to keep on receiving this error?
The error only happened when instead of putting "distanceFormula" in main, I made it it's own class.
#include <iostream>
#include <string>
using namespace std;
class distanceFormula {
public:
int speed;
int time;
int distance;
cout << "What is the speed?" << endl;
cin >> speed;
cout << "How long did the action last?" << endl;
cin >> time;
distance = speed * time;
cout << "The distance traveled was " << distance << endl;
};
int main()
{
distanceFormula ao
ao.distanceFormula;
return 0;
};
The body of the class declaration can only contain members, which can either be data or function declarations, and optionally access specifiers.
Wrap your code inside a function and then call that in main by an object
class distanceFormula {
public:
int speed;
int time;
int distance;
void init()
{
cout << "What is the speed?" << endl;
cin >> speed;
cout << "How long did the action last?" << endl;
cin >> time;
distance = speed * time;
cout << "The distance traveled was " << distance << endl;
}
};
int main()
{
distanceFormula ao;
ao.init();
return 0;
};
If you still have to use a class. Here is how you do it:
#include <iostream>
class distanceFormula
{
private:
int speed; // private
int time; // private
public:
distanceFormula(); // constructor
int getSpeed(); // to get
int getTime(); // to get
int getDistance(); // to get
void setSpeed(int); // to set
void setTime(int); // to set
};
distanceFormula::distanceFormula()
{
this->time = 0;
this->speed = 0;
}
int distanceFormula::getSpeed()
{
return this->speed;
}
int distanceFormula::getTime()
{
return this->time;
}
int distanceFormula::getDistance()
{
return this->time * this->speed;
}
void distanceFormula::setSpeed(int speedVal)
{
this->speed = speedVal;
}
void distanceFormula::setTime(int timeVal)
{
this->time = timeVal;
}
int main()
{
distanceFormula YourObject; // create obj
int SpeedValue;
int TimeValue;
std::cout << "Enter the Speed:";
std::cin >> SpeedValue; // take speed
std::cout << "Enter the Time:";
std::cin >> TimeValue; // take time
YourObject.setSpeed(SpeedValue); // set
YourObject.setTime(TimeValue); // set
std::cout << "This is the distance: " << YourObject.getDistance(); // retrieve result
getchar(); // wait
return 0;
}

Accessing member functions through pointers

Why am I getting the address in the output. Rather I should get the Output Length= (value input by user) , Width = (value input by user).
As in the main body of program after getting input R1.getdata() , ptr->result() should display the result of Rectangle class.
#include <iostream>
using namespace std;
class Rectangle {
protected:
float length;
float width;
public:
void getdata() {
cout << "Enter length and width= ";
cin >> length >> width;
}
void result() {
cout << "Length = " << length << "\nWidth = " << width << endl;
}
};
class Area : public Rectangle {
private:
float area;
public:
void calc_area() { area = length * width; }
void result() { cout << "Area = " << area << endl; }
};
class Perimeter : public Rectangle {
private:
float perimeter;
public:
void calc_peri() { perimeter = 2 * (length + width); }
void result() { cout << "Perimeter = " << perimeter << endl; }
};
void main() {
Rectangle R1;
Area A1;
Perimeter P1;
Rectangle *ptr;
R1.getdata();
ptr = &A1;
ptr->result();
}
You are getting the wrong values, because you are calling ptr->result(); on a uninitialized Area object (A1), which has been upcasted from pointer to Rectangle object.
The values the user inputs though are used in the R1 object, which you then don't use anymore. Moreover, you should make the result() method virtual.
Lastly, the syntax for calling base class method on a pointer to an inheriting class is: ptr->Rectangle::result();.
Below you will find your code with some fixes that demonstrate things I wrote about:
#include <iostream>
using namespace std;
////////////////////////////////////////////////////////////////
class Rectangle {
protected:
float length;
float width;
public:
void getdata() {
cout << "Enter length and width= ";
cin >> length >> width;
std::cout << length << " " << width << std::endl;
}
virtual void result() {
cout << "(Rectangle) Length = " << length << "\nWidth = " << width
<< endl;
}
};
class Area : public Rectangle {
private:
float area;
public:
void calc_area() { area = length * width; }
void result() { cout << "Area = " << area << endl; }
};
class Perimeter : public Rectangle {
private:
float perimeter;
public:
void calc_peri() { perimeter = 2 * (length + width); }
void result() { cout << "Perimeter = " << perimeter << endl; }
};
int main() {
Rectangle R1;
Area* A1;
Perimeter P1;
Rectangle* ptr;
R1.getdata();
ptr = &R1;
A1 = static_cast<Area*>(ptr);
// or:
// A1 = (Area*)ptr;
ptr->Rectangle::result();
}
Ptr points to the address of a child of class Rectangle (the Area class) and therefore it calls the member (result) of the object it refers to (A1 of type Area)