C++ inheritance how to get variables values - c++

I'm trying to create a small program for a lessons.
But In My class that herit , I don't have values of the superclass.
, here's the code
Point.h
#ifndef Point_H
#define Point_H
#include <iostream>
class Point{
public:
Point();
void set_values (int a, int b);
void set_values (int a, int b, int c);
void affichervaleurs();
protected:
int x ;
int y ;
int z ;
};
#endif
Point.cpp
#include <iostream>
#include "Point.h"
using namespace std;
Point::Point(){
x=0;
y=0;
z=0;
};
void Point::set_values (int a, int b){
x=a;
y=b;
}
void Point::set_values (int a = 0, int b = 0, int c = 0){
x=a;
y=b;
z=c;
}
void Point::affichervaleurs(){
cout << "X = " << x << endl;
cout << "Y = " << y << endl;
}
Carre.h
#ifndef Carre_H
#define Carre_H
#include "Point.h"
class Carre:public Point{
public:
int Aire (){
};
void affichercar(){
};
};
#endif
Carre.cpp
#include <iostream>
using namespace std;
#include "Point.h"
class Carre:public Point{
public:
//Carre::Carre(int a, int b);
int Aire (){
return (x * y);
}
void affichercar(){
cout << "Coordonnees X:" << x << endl;
}
};
main.cpp
#include <cstdlib>
#include <iostream>
#include "Carre.h"
#include "Point.h"
using namespace std;
int main()
{
Point MonPoint ;
cout << "Default values:" << endl;
MonPoint.affichervaleurs();
MonPoint.set_values(4,6);
cout << "Setting values:" << endl;
MonPoint.affichervaleurs();
Carre MonCarre;
MonCarre.set_values(4,6,0);
MonCarre.set_values(5,8);
MonCarre.affichercar();
cout << MonCarre.Aire() << endl;
system("PAUSE");
return EXIT_SUCCESS;
}
The problem is, when I call this line :
cout << MonCarre.Aire() << endl;
it returns a strange number. I'm sure that the problem is here :
int Aire (){
return (x * y);
};
Like the x and y are not linked with the superclass.
Can someone help me how to access my x and y values from my superclass in my class Carre ?
Other strange thing this line doesn't appear :
MonCarre.affichercar();
Thanks

You define the functions Aire and affichercar in Carre.h, but you need to declare them only if you want to write an implementation in Carre.cpp.
Edit: and your Carre.cpp is also wrong. You just need to rewrite Carre.* files.
Edit2. Let me do some code review and give you a working version of your code - just summarizing what was discussed in comments and my own thoughts.
Point.h
void set_values (int a, int b);
void set_values (int a, int b, int c);
If you want to define the default values of the arguments of the second function, you should do it in its declaration as was suggested in comments to your question. So it will be
void set_values (int a, int b);
void set_values (int a = 0, int b = 0, int c = 0);
But in this case it's not clear what function should be called if you write, for example, set_values(1, 2), therefore your code won't compile because of ambiguity (as also was mentioned in the comments). So you just have to keep only one extended version of this function with the default arguments. The Point.h will be in this case:
#ifndef Point_H
#define Point_H
#include <iostream>
class Point{
public:
Point();
void set_values (int a = 0, int b = 0, int c = 0);
void affichervaleurs();
protected:
int x ;
int y ;
int z ;
};
#endif
The Point.cpp is also changed a little bit:
#include <iostream>
#include "Point.h"
using namespace std;
Point::Point()
// it's better to initialize these variables here
// : x(0), y(0), z(0)
{
x=0;
y=0;
z=0;
}
void Point::set_values (int a, int b, int c){
x=a;
y=b;
z=c;
}
void Point::affichervaleurs(){
cout << "X = " << x << endl;
cout << "Y = " << y << endl;
}
Now let's consider the Carre.h file
class Carre:public Point{
public:
// IT'S DEFINITION WHICH IS USED WHEN YOU CALL THE FUNCTION
int Aire (){};
// IT'S DEFINITION WHICH IS USED WHEN YOU CALL THE FUNCTION
void affichercar(){};
};
Now I'm starting answering your questions:
The problem is, when I call this line :
cout << MonCarre.Aire() << endl;
it returns a strange number.
Yes, it's a strange number returned by the function defined in the Carre.h (not Carre.cpp) file.
I'm sure that the problem is here :
int Aire (){
return (x * y);
};
No, as you see, it's not.
Like the x and y are not linked with the superclass.
In fact they are.
Can someone help me how to access my x and y values from my superclass in my class Carre ?
You already have this access. It's okay to use protected members from base class in derived class in case of public inheritance.
Other strange thing this line doesn't appear : MonCarre.affichercar();
You mean it does nothing? But it's in perfect consistency with how you implement (define) the function in Carre.h (not Carre.cpp) file.
So let me change the code to make it work.
Carre.h
#ifndef Carre_H
#define Carre_H
#include "Point.h"
class Carre:public Point{
public:
int Aire (); // now it's declaration
void affichercar(); // now it's declaration
};
#endif
Carre.cpp
#include <iostream>
using namespace std;
int Carre::Aire (){
return (x * y);
}
void Carre::affichercar(){
cout << "Coordonnees X:" << x << endl;
}
I didn't compile this for myself, but the whole idea should be clear.

access my x and y values
From within Carre, you simply access them by 'x' and 'y'.
From outside, you cannot as they are not public.

Related

C++: undefined reference to Constructor

I just started working with C++ and am working on an exercise that deals with polymorphic pointers. I'm having trouble trying to solve an error message I believe I'm getting from my Rectangle.cpp as I call the class from my main.cpp.
The error message:
undefined reference to 'Rectangle::Rectangle(double, double)'
Main.cpp
#include <iostream>
#include "Rectangle.h"
using namespace std;
//////////////////////////////////////////////
// --- FUNCTIONS DECLARATION---
void introduceShape(Shape*);
double calculateShapeArea(Shape*);
double calculateShapeCircumferece(Shape*);
int main()
{
Rectangle rectangle1(5,2);
// Rectangle *rec1 = new Rectangle(5,2);
introduceShape(&rectangle1);
cout << "My area is: " << calculateShapeArea(&rectangle1) << ", my circumference is: " << calculateShapeCircumferece(&rectangle1) << endl << endl;
return 0;
}
//////////////////////////////////////////////
// --- FUNCTIONS ---
void introduceShape(Shape* shapeToIntroduce)
{
return shapeToIntroduce->introduce();
}
double calculateShapeArea(Shape* shapeToCalculate)
{
return shapeToCalculate->calculateArea();
}
double calculateShapeCircumferece(Shape* shapeToCalculate)
{
return shapeToCalculate->calculateCircumference();
}
Rectangle.h
#ifndef RECTANGLE_H_INCLUDED
#define RECTANGLE_H_INCLUDED
#include "Shape.h"
#include <iostream>
using namespace std;
class Rectangle: public Shape
{
double width;
double height;
public:
Rectangle(double , double );
void introduce();
double calculateArea();
double calculateCircumference();
};
#endif // RECTANGLE_H_INCLUDED
Rectangle.cpp
#include "Rectangle.h"
#include <iostream>
using namespace std;
Rectangle::Rectangle(double width, double height)
{
this->width = width;
this->height = height;
}
void Rectangle::introduce()
{
cout << "I AM A RECTANGLE !" << endl;
}
double Rectangle::calculateArea()
{
return width*height;
}
double Rectangle::calculateCircumference()
{
return 2*(width+height);
}
Shape.h
#ifndef SHAPE_H_INCLUDED
#define SHAPE_H_INCLUDED
class Shape
{
public:
virtual void introduce() = 0;
virtual double calculateArea() = 0;
virtual double calculateCircumference() = 0;
};
#endif // SHAPE_H_INCLUDED
The error is generated by the linker because it can not see where the definition of the constructor is located.
If you are using an IDE, you should add .cpp file to the project so that it can be compiled and the definition would be found by the linker. It not, then you have to compile it yourself -assuming you are using gcc:
g++ Rectangle.cpp
will combine cpp files into one executable and should not show you that error.
Visit this post

Unknown Override specifier when accessing methods/object across classes

What I want to do (c++ problem):
Enter main. Call Class A (and pass a value). Inside class A, I call Class B (and pass a value). Do some stuff in class B. Return value back to Class A. Do some more stuff in A. Return back to main function.
I get the error that obj3 is an unknown override specifier. I tried to create a simple program to showcase my problem;
#include <math.h>
#include <string>
#include <stdio.h>
#include <iomanip>
#include <iostream>
using namespace std;
class A
{
B obj3;
public:
int add3(int num)
{
int x = num + 1;
int y = obj3.add2(x);
return y;
}
};
class B
{
public:
int add2(int num2)
{
int y = num2 + 2;
return y;
}
};
int main()
{
int g;
A obj1;
cout << "enter a number: " << endl;
cin >> g;
int r = obj1.add3(g);
cout << r;
system("pause");
return 0;
}

Pointer to different components of a class

I have an assignment from school to create pointers to different components of a class.
I don't understand how it works. Can someone help me with a simple program?
I have made the basic layout of what's needed. I don't know how to go about creating pointers.
#include <iostream>
#include <math.h>
using namespace std;
class Rectangle
{
int a,b;
public:
};
class Perimeter : public Rectangle
{
public:
int c;
void P(int a, int b)
{
c = 2 * (a + b);
cout << "This Is The Perimeter Of The Rectangle: " << c << endl;
}
};
class Area : public Rectangle
{
public:
int c;
void A(int a, int b)
{
c = a * b;
cout << "This Is The Area Of The Rectangle: " << c << endl;
}
};
class Diagonal : public Rectangle
{
public:
float c;
void D(int a, int b)
{
c = sqrt((a*a)+(b*b));
cout << "This Is The Diagonal Of Rectangle: " << c << endl;
}
};
#include<iostream>
#include<math.h>
using namespace std;
class Rectangle
{
int a,b;
public:
};
class Perimeter : public Rectangle
{
public:
int c;
void P(int a, int b)
{
c = 2 * (a + b);
cout<<"This Is The Perimeter Of The Rectangle: "<<c<<endl;
}
};
class Area : public Rectangle
{
public:
int c;
void A(int a, int b)
{
c = a * b;
cout<<"This Is The Area Of The Rectangle: "<<c<<endl;
}
};
class Diagonal : public Rectangle
{
public:
float c;
void D(int a, int b)
{
c = sqrt((a*a)+(b*b));
cout<<"This Is The Diagonal Of Rectangle: "<<c<<endl;
}
};
int main()
{
int e,f;
cout<<"Enter Length And Breadth: "<<endl;
cin>>e>>f;
/***************************************/
Perimeter p; //CREATING AN OBJECT
Perimeter *Peri; //CREATING A POINTER TO THE OBJECT
Peri=&p; //ASSIGNING ADDRESS TO THE POINTER
Peri->P(e,f); //MEMBER ACCESS USING POINTER TO AN OBJECT
/**************************************/
Area a;
int Area::*ptr=&Area::c; //CREATING A POINTER TO THE DATA MEMBER
a.*ptr = e;
a.A(e,f);
/*************************************/
Diagonal d;
void (Diagonal::*Dia)(int,int)=&Diagonal::D; //CREATING POINTER TO MEMBER FUNCTION
(d.*Dia)(e,f); //THIS IS HOW WE CALL THE MEMBER FUNCTION USING ITS POINTER
/*************************************/
return 0;
}
I believe this is what you were looking for.
there are some errors you made in the program. i didn't correct them but i am pointing them out.
though you didn't write anything(create any functions) in the parent class, creating pointer to an object of the sub-class is useless. in this case, early binding is taking place. you can go with a pure virtual function following function Over-Riding.
A pointer is a reference to an area in memory.
In the picture, foo is holds the value 1702 which is the spot in memory the string "hello" is stored. Pointers to elements in a class work the same way. Your class will occupy some part of memory and a pointer to the class member will hold the value of where the class member is in memory.
I'm not sure which type of pointer you're supposed to use for your class, but there's three different types.
Raw pointers:
These are the types similar to shown in the picture. An example would be:
int * x = 5; // Let's say 5 is stored at memory location 0x15
cout << x; // This will give 0x15
cout << *x; // This "dereferences" the pointer also known as go to that memory location and retrieve the value. This outputs 5
There are also Smart Pointers as defined here:
https://learn.microsoft.com/en-us/cpp/cpp/smart-pointers-modern-cpp?view=vs-2019
These are meant to be safer since they will be garbage collected, and prevent common dereferencing errors.
For using pointers in a class it could be as easy as:
class shape {
int * height;
int * width;
public:
void setHeight (int x) {height = &x; }
void setWidth(int x) { width = &x; }
int getHeight(){ return *height; }
int getWidth() { return *width; }
};
class square : class shape {
public getArea(int *h, int *w) {returns *h * *w; }
};
int main {
int x = 5;
int y = 6;
int * pointerX = &x; //& means this variable's memory address
int * pointerY = &y;
rect rectangle;
std::cout << rectangle.getArea(pointerX, pointerY) << std::endl;
rectangle.setHeight(7);
std::cout << "Rect height:" << rectangle.getHeight() << std::endl;
rectangle.setWidth(9);
std::cout << "Rect width:" << rectangle.getWidth() << std::endl;
rect * ptrRect = &rectangle;
std::cout << ptrRect->getArea(pointerX, pointerY) << std::endl;
ptrRect->setHeight(9);
std::cout << "ptrRect height:" << ptrRect->getHeight() << std::endl;
ptrRect->setWidth(10);
std::cout << "ptrRect width:" << ptrRect->getWidth() << std::endl;
std::cout << square.getArea(pointerX, pointerY) << std::endl;
}

Using for_each to call a print function from a list of object

I need to use a for_each function to call the print function of each object in the list of objects shapeList. When I put function output as the final parameter of for_each, I get a "cannot determine which instance of overloaded function "output" is intended.
void output(Point* point)
{
point->print();
}
This is my output function for for_each
for_each(shapeList.begin(), shapeList.end(), output);
The for_each statement
I have looked at other solutions that involve using binds and lambdas, but this is a class assignment and I cannot use those methods.
Any help is greatly appreciated.
#include <iostream>
#include <string>
#include <fstream>
#include <list>
#include <algorithm>
#define sz 12
using namespace std;
class Point
{
private:
int x, y;
public:
Point() { }
Point(int a, int b)
:x(a), y(b) { }
// print function is pure virtual and that makes class Point an abstract class
// a pure virtual function can have prototype only without definition
// an abstract class can't be instantiated
// its derived class must override this function in order to be a real class
virtual void print() const = 0;
};
void Point::print() const
{
cout << "\nPoint: ( "
<< x
<< " , "
<< y
<< " )";
}
///////////////////////////////////////////////////////////////////
class Circle : public Point
{
private:
int radius;
public:
Circle() : Point() { }
Circle(int a, int b, int c)
:Point(a, b), radius(c) { }
virtual void print() const;
};
void Circle::print() const
{
cout << "\nCenter of the Circle is at: ";
Point::print();
cout << "\nRadius of the Circle is: "
<< radius;
}
/////////////////////////////////////////////////////////////////////
class Cylinder : public Circle
{
private:
int height;
char color[sz];
public:
Cylinder() { }
Cylinder(int a, int b, int r, int h, char clr[])
: Circle(a, b, r), height(h)
{ strcpy(color, clr); }
virtual void print() const;
};
void Cylinder::print() const
{
Circle::print();
cout << "\nHeight of Cylinder is: "
<< height
<< "\nColor of Cylinder is: "
<< color
<< endl;
}
void load_list(list<Point*>&, char*); //
void output(Point*&);
///////////////////////////////////////////////////////////////
int main()
{
char clr[10];
list<Point*> shapeList;////
load_list(shapeList, clr);
for_each(shapeList.begin(), shapeList.end(), output);
return 0;
}
void load_list(list<Point*>& ptList, char *ch)
{
char type;
int x, y, r, h;
ifstream infile("shapes.txt");
if (!infile)
{
cout << "\nCan not open input file.";
exit(1);
}
infile >> type;
while (infile)
{
if (type == 'c')
{
infile >> x >> y >> r;
ptList.push_back(new Circle(x,y,r));
}
else if (type = 'l')
{
infile >> x >> y >> r >> h >> ch;
ptList.push_back(new Cylinder(x, y, r, h, ch));
}
infile >> type;
}
}
void output(Point* point)
{
point->print();
}
You declare the function to take a pointer by reference(?) And the implementation takes a pointer.

c++ error: object of abstract class type "..." is not allowed

I want to use polymorphism in my program but don't know why when I create
virtual void setVertices()=0;
in class CFigure i get an error
C2259: 'CRectangle': cannot instantiate abstract class (line 63 and 74)
IntelliSense: object of abstract class type "CRectangle" is not allowed:
pure virtual function "CFigure:setVertices" has no overrider (line 63 and 74)
I want also to declare:
virtual void setVertices(CFigure& fig) = 0;
I don't know at all that if I can write CFigure& fig cuz CRectangle i have:
void setVertices(CRectangle& fig)
and those two methods have different parameters.
Can someone can tell me how to help me to explain those errors and tell me how to fix my program? Code:
#include<iostream>
#include<vector>
#include<cmath>
using namespace std;
class Point2D{
int x, y;
public:
void setX(int X){ x = X; }
void setY(int Y){ y = Y; }
int getX(){ return x; }
int getY(){ return y; }
};
class CFigure :public Point2D
{
protected:
Point2D Vert[4];
public:
CFigure(){}
//virtual void setVertices(CFigure& fig) = 0;
virtual void setVertices()=0;// if I comment this line all works good
};
class CRectangle : public CFigure
{
public:
CRectangle(){}
void setVertices(CRectangle& fig)
{
//CRectangle fig;
int x1, y1, a;
cout << "Give x1, y1" << endl;
cin >> x1 >> y1;
cout << "Give a" << endl;
cin >> a;
fig.Vert[0].setX(x1);
fig.Vert[0].setY(y1);
fig.Vert[1].setX(x1 + a);
fig.Vert[1].setY(y1);
fig.Vert[2].setX(x1);
fig.Vert[2].setY(y1 + a);
fig.Vert[3].setX(x1 + a);
fig.Vert[3].setY(y1 + a);
}
void showPoints()
{
CRectangle f;
setVertices(f);
for (int i = 0; i < 4; i++)
{
cout << "P" << i << "( " << f.Vert[i].getX() << " " << f.Vert[i].getY() << " ) " << endl;
}
}
};
int main()
{
CRectangle ag;
ag.showPoints();
return 0;
}
CFigure declares setVertices() as:
virtual void setVertices()=0;
But CRectangle declares setVertices() as:
void setVertices(CRectangle& fig)
The additional parameter makes it so CRectangle::setVertices() is not overriding CFigure::setVertices(). It is overloading it instead. That is why the compiler is complaining that CRectangle is an abstract class - it really is. When you override a virtual method, the signature of the overriding method must exactly match the signature of the method that is being overridden, eg:
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
class Point2D
{
int x, y;
public:
void setX(int X){ x = X; }
void setY(int Y){ y = Y; }
int getX(){ return x; }
int getY(){ return y; }
};
class CFigure : public Point2D
{
protected:
Point2D Vert[4];
public:
CFigure() {}
virtual void setVertices()=0;
};
class CRectangle : public CFigure
{
public:
CRectangle() {}
void setVertices()
{
int x1, y1, a;
cout << "Give x1, y1" << endl;
cin >> x1 >> y1;
cout << "Give a" << endl;
cin >> a;
Vert[0].setX(x1);
Vert[0].setY(y1);
Vert[1].setX(x1 + a);
Vert[1].setY(y1);
Vert[2].setX(x1);
Vert[2].setY(y1 + a);
Vert[3].setX(x1 + a);
Vert[3].setY(y1 + a);
}
void showPoints()
{
setVertices();
for (int i = 0; i < 4; i++)
{
cout << "P" << i << "( " << Vert[i].getX() << " " << Vert[i].getY() << " ) " << endl;
}
}
};
int main()
{
CRectangle ag;
ag.showPoints();
return 0;
}