C++ Inheritances - Files - c++

Im trying to seperate a class and its superclass into two different header and cpp files. In the main Method I want to include both of them.
Currently my main programm example.cpp looks like this:
#include <iostream>
#include "header.h"
using namespace std;
int main(void)
{
Rectangle Rect;
Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
cout << "Total area: " << Rect.getArea() << endl;
return 0;
}
My Rectangle.cpp like this:
#include <iostream>
#include "Shape.h"
#include "Rectangle.h"
using namespace std;
int getArea()
{
return (Shape::width * Shape::height);
}
And my Rectangle.h:
class Rectangle: public Shape
{
public:
int getArea();
};
The Shape.cpp:
#include <iostream>
#include "Shape.h"
using namespace std;
void Shape::setWidth(int w)
{
width = w;
}
void Shape::setHeight(int h)
{
height = h;
}
And the Shape.h:
class Shape
{
public:
void setWidth(int w);
void setHeight(int h);
int width;
int height;
};
The header.h just includes the two headers of the classes:
#include "Shape.h"
#include "Rectangle.h"
If I compile it, the compiler says:
Lukass-MacBook-Pro:Oberklassenbeispiel Lukas$ g++ -c Rectangle.cpp
Rectangle.cpp:9:17: error: invalid use of non-static data member 'width'
return (Shape::width * Shape::height);
~~~~~~~^~~~~
Rectangle.cpp:9:32: error: invalid use of non-static data member 'height'
return (Shape::width * Shape::height);
~~~~~~~^~~~~~
2 errors generated.
It seems, that the Rectanlge.cpp cant see the attributes of the superclass. How do I fix this?

When you #include, you provide the file name, not the classes specified in the file. It is quite common to have multiple closely coupled classes in a single file. Your example isn't really the best (it is single inheritance, not multiple as the title suggests), but working with that...
You could have a file, shapes.h with the following contents :
class Shape
{
public:
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};
// Derived class
class Rectangle: public Shape
{
public:
int getArea()
{
return (width * height);
}
};
Then in your main function (and the file containing it).
#include <iostream>
#include "shapes.h"
int main(void)
{
Rectangle Rect;
Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
cout << "Total area: " << Rect.getArea() << endl;
return 0;
}

Related

How to get area of rectangle using class?

I have been tasked to calculate the area and perimeter of a rectangle using class. The input function is supposed to be inside class. I wrote code so far but there seem to be errors I can't detect.
Some help would be appreciated.
rectangle.h
#ifndef RECTANGLE_H
#define RECTANGLE_H
class Rectangle{
public:
int width, length;
Rectangle();
Rectangle(int width1,int length1);
void getRectangle();
int getArea();
int getPerimeter();
};
#endif // RECTANGLE_H
rectangle.cpp
// oporer ta class
#include<iostream>
#include "rectangle.h"
Rectangle::Rectangle()
{
width=0;
length=0;
}
Rectangle::Rectangle(int width1,int length1)
{
width=width1;
length=length1;
}
void Rectangle::getRectangle()
{
cin>>width>>length;
}
int Rectangle::getArea()
{
return (width*length);
}
int Rectangle::getPerimeter()
{
return (width+length)*2
}
// oporer ta rectangle cpp
main.cpp
#include <iostream>
#include "rectangle.h"
using namespace std;
int main()
{
Rectangle paraFirst();
paraFirst.getRectangle();
return 0;
}
// main fucntion
Assuming that the #includes work in your local setup, I see two typos here:
cin>>width>>length; must std::cin >> width >> length;
missing semicolon after return (width+length)*2
And probably the main problem:
Rectangle paraFirst();
is parsed as a declaration for a function that takes no arguments and returns a Rectangle. See also Most vexing parsing. To call the default constructor simply use
Rectangle paraFirst;
or
Rectangle paraFirst{};

Class has no member named

I am new to c++ and is trying to learn about its Object-Oriented design. I started a small project to test out inheritance and polymorphism but encountered a problem and can't seen to figure out what went wrong.
Whenever I compile, there will be an error "class 'ShapeTwoD' has no member name getx() and gety()". I tried to directly set the x and y value with setx and sety but it still return the same error.
Class ShapeTwoD is the Base class with only the variable 'name' and 'container'. Would appreciate if anyone can direct me to the right direction.
Main.cpp
#include <iostream>
#include <string>
#include "ShapeTwoD.h"
#include "Square.h"
using namespace std;
int main()
{
cout<<endl;
ShapeTwoD *shape2D[100];
ShapeTwoD *sq1 = new Square("Square", true, 4, 6);
cout << sq1->getName() <<endl;
cout << sq1->getContainer() <<endl;
//sq1->setx(4) <<endl;
//sq1->sety(6) <<endl;
cout << sq1->getx() <<endl;
cout << sq1->gety() <<endl;
cout<<endl;
delete sq1;
}
Square.h
#include <iostream>
#include <string>
#include "ShapeTwoD.h"
using namespace std;
class ShapeTwoD; //forward declare
class Square : public ShapeTwoD
{
public:
int x;
int y;
//constructor
Square(string name, bool container,int x, int y);
int getx();
int gety();
void setx(int x);
void sety(int y);
};
Square.cpp
#include <iostream>
#include <string>
#include "Square.h"
#include "ShapeTwoD.h"
Square::Square(string name, bool containsWarpSpace, int coordx, int coordy)
:ShapeTwoD(name, containsWarpSpace)
{
(*this).x = coordx;
(*this).y = coordy;
}
int Square::getx()
{
return (*this).x;
}
int Square::gety()
{
return (*this).y;
}
void Square::setx(int value)
{
(*this).x = value;
}
void Square::sety(int value)
{
(*this).y = value;
}
That's normal... If you declare sq1 as ShapeTwoD, you have access to ShapeTwoD public member methods/attributes. Even it was instanciated with the Square constructor. Cast it as Square, and you can use getx gety. Or declare getx/gety as methods of ShapeTwoD.
Well this is what you should expect since it has shape2D type , Although constructing it with the square constructor won't allow you to access the derived class members but it will allow you to have a safe type cast to use it.. the simplest way to do it is by :
cout << static_cast<Square*>(sq1)->getx() << endl;
cout << static_cast<Square*>(sq1)->gety() << endl;

C++ Class object as argument in other class function

I have a C++ project in Visual Studio 2015.
GameManager.h and Input.h both give me a syntax error: identifier 'Player'. This happens because I want to give an object of type 'Player' as an argument to functions in these two Header files and their appropriate C++ Files.
How do I fix that? For further information I have provided my code.
main.cpp:
#include "GameManager.h"
#include "Input.h"
#include "Player"
#include <iostream>
#include <string>
using namespace std;
const int maxPlayerCnt = 10;
static Player p1, p2, morePlayers[maxPlayerCnt];
int main()
{
GameManager game;
game.Game(p1, p2, morePlayers);
return 0;
}
It creates an object of type GameManager and 3 objects of type Player.
GameManager.h:
#include "Player.h"
class GameManager
{
public:
void Game(Player p1, Player p2, Player morePlayers[]);
};
GameManager.cpp:
#include "GameManager.h"
void GameManager::Game(Player p1, Player p2, Player morePlayers[])
{
int playerCnt = 0;
Input input;
input.getPlayerDetails(playerCnt, p2);
input.getMorePlayerDetails(playerCnt, morePlayers);
}
It creates an object of type Input to use further functions and will get more code, once I figure this problem out. And then calls to functions with specific arguments it gets from main.cpp
Input.h:
#pragma once
#include "Player.h"
#include <iostream>
#include <string>
using namespace std;
class Input
{
public:
Input();
void getPlayerDetails(int &playerNum, Player p);
void getMorePlayerDetails(int &playerNum, Player p[]);
};
It includes everything Input.cpp needs and initializes the funcitons
Input.cpp:
#include "Input.h"
void Input::getPlayerDetails(int &playerNum, Player p)
{
playerNum++;
string currentName;
char currentSymbol;
cout << "Player " << playerNum << ", what is your name?\n";
cin >> currentName;
p.setName(currentName);
cout << currentName << " what is your symbol?\n";
cin >> currentSymbol;
p.setSymbol(currentSymbol);
}
void Input::getMorePlayerDetails(int &playerNum, Player p[])
{
int plNum = playerNum;
if (playerNum >= 12)
cout << "You can't get another player!\n";
else
{
//getPlayerDetails(p[playerNum - 2], (plNum - 2));
}
}
It for now has all the functions needed and both get an object of type Player. And the second function is not quite done now. But that is not important.
Player.h:
#pragma once
#include <iostream>
#include <string>
using namespace std;
class Player
{
private:
string _name;
char _symbol;
public:
Player();
void getName();
void setName(string name);
void setSymbol(char symbol);
};
Player.cpp:
#include "Player.h"
Player::Player()
{
}
void Player::getName()
{
cout << "I have no name!\n";
}
void Player::setName(string name)
{
_name = name;
}
void Player::setSymbol(char symbol)
{
_symbol = symbol;
}
If you can help me, I would be pleased to see your response.

How to use members from other files in main c++ code file?

I want to know how to use members from other files in main c++ code file?
I already know that we can put our declarations in header files.
Let me summarize my current knowledge and missing parts:
Example 1 - using a function from another file
other.cpp
int Add(int a,int b)
{
return a+b;
}
main.cpp
int Add(int,int); //the most important part
int main()
{
Add(12,2);
}
Example 2 - using a global variable from another file
other.cpp
int something=12;
main.cpp
extern int something; //the most important part
int main()
{
cout << something;
}
Question 1 - create an object from a class in another file???
other.cpp
class Rectangle
{
public:
int width;
int height;
int area() { return height*width }
};
main.cpp
int main()
{
Rectangle a; //gives me error,what should i do?
}
You should start using header files. Typically you would have
Rectangle.h a header file with the declarations
class Rectangle{
public:
Rectangle();
Rectangle(int x, int y);
int width;
int height;
int area();
};
Rectangle.cpp Then you'd have a corresponding cpp file with the definitions
#include "Rectangle.h"
Rectangle::Rectangle()
{
width = 0;
height = 0;
}
Rectangle::Rectangle(int x, int y)
{
width = x;
height = y;
}
Rectangle::area()
{
return height*width;
}
Now in your main.cpp
#include "Rectangle.h"
int main()
{
Rectangle a;
}
You need to declare a class Rectangle in main.cpp, preferably using a header file, ex:
other.h
class Rectangle
{ public:int width; int height; int area(); };
other.cpp
#include other.h
int Rectangle::area() { return height*width; }
main.cpp
#include "other.h"
int main()
{
Rectangle a; //gives me error,what should i do?
}
Following your pattern, it should be simply class Rectangle; (forward declaration).
However, you really should consider to create a Rectangle.h and Rectangle.[C|cpp|cc] (any of them), and include the header instead of forward declaring.
The header should contain the declaration, the source the definition.
Place the declaration of the class in a header file. The definition is usually placed in a source file which uses #include to reference the declaration header. Any other source file which require usage of the class will then simply #include the class declaration header.

error is - "first defined here" in simple Hierarchy classes

Im new in cpp, and tried to google the problame with no luck solving it, could use help.
Oh, and my files are all in the same folder.
the Rectangle.h file:
#ifndef RECTANGLE_H_
#define RECTANGLE_H_
#include "Polygon.h"
class Rectangle: public Polygon{
public:
Rectangle(int nColor);
Rectangle(Rectangle& r);
virtual string getType();
int getArea();
};
#endif /* RECTANGLE_H_ */
The errors are here, under each method signature it sais:
"first defined here"
the Rectangle.cpp file:
#include "Rectangle.h"
#include "Polygon.h"
//error is - "first defined here"
Rectangle::Rectangle(int color):Polygon(color, 3, "Rectangle"){
}
//error is - "first defined here"
Rectangle::Rectangle(Rectangle& r) :
Polygon(r) {
}
//error is - "first defined here"
string Rectangle::getType() {
return "Rectangle";
}
//error is - "first defined here"
int Rectangle::getArea() {
return 0;
}
I am also adding the father class "Polygon.h" but im pretty sure it's not relevant...
the only interesting thing about it is the method:
virtual string getType();
which is not abstract. just virtual
Polygon h:
#ifndef __POLYGON_H
#define __POLYGON_H
#include "Point.h"
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Polygon {
public:
Polygon(int nColor , int nPoints , std::string type);
Polygon(const Polygon &polyOther);
virtual ~Polygon() = 0;
int getColor();
virtual string getType();
void addPoint(Point* p);
Point* getPoint(int index) const;
int getNumOfPoints() const;
Polygon& operator=(const Polygon &polyOther);
private:
std::vector<Point*> _points;
const int _color;
string _type;
};
#endif
thanks for the help....