Constructor is not working properly - c++

I need help building a constructor that would initialized the respective data when instantiated within
the main().
#include <iostream>
using namespace std;
class Entity{
public:
int x, int y, char icon; };
int main(){
Entity pData;
pData.x=4; pData.y=3, pData.icon='1';
cout<<pData.x<<'\n'\; cout<<pData.y<<'\n'\; cout<<pData.icon<<\'n'\;
}
I included an example of what i need only... there no need to include all the program. Anyways I need the constructor to initialized the data in the main as soon as the instance(pData) of Entity is created: I know the constructor has to be something like
Entity::Entity(int x, int y, char icon){};
and once instantiated in the main it would be something like
Entity pData{3,4,'1'};
but obviously this isn't working for me
oh by the way I need a constructor because that's what the assignment is asking in the first place here you go copied right off from the doc file
"write a parameterized constructor for the Entity class that sets x, y, and icon, and use it when creating the instance"

Actually u have not defined constructor for your class Entity(But compiler have defined it for you but it only allocate memory for member variable of Entity).
class Entity {
public:
int x,y;
char icon;
Entity(int _x, int _y,char _icon)
{
x=_x;
y=_y
icon=_icon;
}
};
int main()
{
Entity obj(4,3,'I');
return 0;
}
`

Entity::Entity(int a, int b, char c)
{
x = a;
y = b;
icon = c;
};
Define your constructor like this...
And call it like:-
Entity pData( 1,2,'a');

You don't need to add a constructor because your class is an aggregate. This would work (after fixing some typos)
class Entity
{
public:
int x, y;
char icon;
};
#include <iostream>
int main()
{
using std::cout;
Entity pData{3,4,'1'};
cout << pData.x <<'\n';
cout << pData.y <<'\n';
cout << pData.icon <<'\n';
}

You can for example define a constructor the following way
class Entity{
public:
Entity( int x, int y, char icon ) : x( x ), y( y ), icon( icon ) {}
int x, int y, char icon;
};
And use it like
Entity pData( 4, 3,'1' );
or
Entity pData { 4, 3,'1' };
or
Entity pData = { 4, 3,'1' };
Take into account that for your original class definition you could write
Entity pData = { 4, 3,'1' };
without defining explicitly a constructor.

Related

how to get a class to take in another classes parameters?

I want to have my grid class constructor to take in drivers_location parameters , but it keeps giving me these errors.
https://imgur.com/a/y4MZqso
#include <iostream>
#include <string>
using namespace std;
class drivers_location {
public:
drivers_location() = default;
drivers_location(string name, float xx, float yy){
x = xx;
y = yy;
name = driver_name;
}
private:
float x{};
float y{};
string driver_name;
};
class grid {
public:
grid() = default;
grid(drivers_location(string name, float xx, float yy));
private:
};
int main() {
drivers_location p;
float pointx{ 2.0 };
float pointy{ 3.0 };
grid m[5];
m[0] = { {"abdul" , pointx, pointy }};
}
I want the grid to take in parameters of drivers_location without using inheritance if that's possible
The correct syntax for declaring a constructor takes argument of type driver_location is as shown below. Note that you don't have to specify the 2 parameters of driver_location when defining the constructor for grid that has a parameter of type driver_location.
class grid {
public:
grid() = default;
//---vvvvvvvvvvvvvvvv---->this is how we specify that this ctor has a parameter of type drivers_location
grid(drivers_location){
//add your code here
}
private:
};
I would also recommend using a good c++ book.

Error the default constructor of "Card" cannot be referenced -- it is a deleted function [duplicate]

So i created the class Point and want to use it as the parameter of the constructor in the class Circle , but the error : There is no default constructor for class "Point" shows up and I dont know how to fix it. The code is represented below this text:
class Point {
private:
int x, y;
public:
Point(int X, int Y) {
x = X;
y = Y;
}
};
class Circle {
private:
int radius;
Point centre;
public:
Circle(Point q, int r) {
centre = q;
radius = r;
}
};
int main() {
Point obj = Point(3, 4);
Circle obj = Circle(obj, 3);
}
The first problem is that when the constructor Circle::Cirlce(Point, int) is implicitly called by the compiler, before executing the body of that ctor, the data members centre and radius are default initialized. But since you've provided a user-defined ctor Point::Point(int, int) for class Point, the compiler will not synthesize the default ctor Point::Point(). Thus, the data member centre cannot be default initialized.
To solve this you can use constructor initializer list as shown below. The constructor initializer list shown below, copy initialize the data member centre instead of default initializing it.
class Point {
private:
int x, y;
public:
Point(int X, int Y) {
x = X;
y = Y;
}
};
class Circle {
private:
int radius;
Point centre;
public:
//--------------------------vvvvvvvvvvvvvvvvvvvv--->constructor initializer list used here
Circle(Point q, int r): radius(r), centre(q)
{
}
};
int main() {
Point obj = Point(3, 4);
Circle circleObj(obj,4);
}
Demo
Additionally, you had 2 objects with the same name obj inside main.

Have a problem on how to set a default class

In the shape.cpp I need set a default constructor for class Point, But I don't know how to do that.
Thanks
Point::Point(double _f, double _g){
f = 1;
g = 1;
}
Rectangle::Rectangle():Point(1, 1) {
x = 1;
y = 1;
}
Rectangle::Rectangle( Point q, double l, double w):x(l),y(w),Point(q) {
}
#include <iostream>
using namespace std;
class Point{
int f,g; //declaring point(f,g)
public :
Point(); //This will be your default constructor
Point(double _f,double _g); // Constructor for class Point
int getf(){ //just for purpose of display function() below. You can remove this once you understand code.
return f;
}
int getg(){ //just for purpose of display function() below. You can remove this once you understand code.
return g;
}
};
class Rectangle{
double l,w; //declaring variable to store length and width of Rectangle
Point pt; //whatever your use of point is
public :
Rectangle(Point q,double l,double w); //constructor for class Rectangle
void display(){ // displaying the class...just for demonstration
cout<<"l = "<<l<<endl;
cout<<"w = "<<w<<endl;
cout<<"pt = ("<<pt.getf()<<", "<<pt.getg()<<")\n";
}
};
//Defining the constructor of class Point
Point::Point(double _f, double _g):f(_f),g(_g){} // I have used initialiser list here
Point::Point():f(0),g(0){} // (your needed default constructor)
Rectangle::Rectangle( Point q, double l, double w):l(l),w(w),pt(q) {} //Defining the constructor of class Rectangle
int main()
{ //Demonstrating object creation and displaying of object r of class rectangle
Point p(1,2);
Rectangle r(p,5,10);
r.display();
}
I have attached the code that would help you understand about constructors and how to define them.
Hope this solves your question !
class Point{
int f,g;
public:
Point();
};
Point::Point(){
f = 1;
g = 1;
}
int main(){
Point *p = new Point() ;
}

How to validate the initialization of a const member variable before assigning it in C++

Let's say I have this simple class with a const int member variable:
class MyClass{
public:
Myclass(int x, int y);
private:
const int importantNumber;
int anotherNumber;
};
MyClass::MyClass(int x, int y) :importantNumber{x}
{
this->anotherNumber = y;
}
Since int importantNumber is const, I can only set it during the creation of the object by the constructor (with a member initialization list, as seen above).
Now, the question: how could I possibly add validation for argument x given to the constructor before actually creating importantNumber with that value? Is it possible to create a static int MyClass::validation(int a) and use it on the member initialization list of the constructor like importantNumber{validation(x)}?
Even if it's possible, is there a better way to do it?
You just add it.
MyClass::MyClass(int x, int y) : importantNumber{validate(x)}
{
this->anotherNumber = y;
}
The int validate(int original) function can now return something other than x or throw an exception or assert or ask the user for confirmation, whichever you deem appropriate.
If it is just a simple check and you don't want to write a validate function you can use a lambda:
MyClass::MyClass(int x, int y) :importantNumber{
[](int number){
assert(number > 0);
return number;
}(x)}
{
this->anotherNumber = y;
}
Although this can get a bit convoluted if you overdo it.
You can use the ternary operator condition ? true : false in the constructor if you want to validate with a simple condition:
class MyClass{
public:
MyClass(int x, int y);
private:
const int importantNumber;
int anotherNumber;
};
MyClass::MyClass(int x, int y) : importantNumber(x > 0 ? x : 0)
{
this->anotherNumber = y;
}
However, be warned that things can quickly become difficult to read if you overdo it with this operator.
For something more complex, you could do something like this:
int validateIntegral(int x) const
{
// Do validation on 'x'...
return x;
}
class MyClass{
public:
MyClass(int x, int y);
private:
const int importantNumber;
int anotherNumber;
};
MyClass::MyClass(int x, int y) : importantNumber(validateIntegral(x))
{
this->anotherNumber = y;
}
Use factory function for creating a class instead of constructor.
class MyClass
{
public:
static MyClass* create (int x, int y);
private:
MyClass(int x, int y);
private:
const int importantNumber;
int anotherNumber;
};
MyClass* MyClass::create (int x, int y)
{
return x > 0 ? new MyClass(x, y) : NULL;
}
When you need some advanced validation of parameters, factories have following advantages:
They avoid creation of object in memory if tests fail
They have more flexibility over checking parameters in initialization
list
You can return NULL if you dont need exceptions nor you want to have some ".is_valid()" member function for your class.

Store cursor position in class object (ncurses c++)

I am using QTCreator to compile my c++ code and the <curses.h> library.
Let us say we have the following class definition (.h):
struct coordinateYX
{
int y;
int x;
coordinateYX(long int yPos, long int xPos);
coordinateYX() {}
}
class Rogue
{
private:
long int health;
coordinateYX heroPosition;
public:
long int getHealth();
void setHealth(long int initHealth);
void healthChange(long int vDelta);
coordinateYX getHeroPosition();
void setHeroPosition(coordinateYX hPos);
};
and (.cpp):
coordinateYX::coordinateYX(long int yPos, long int xPos) : y{yPos}, x{xPos} {}
long int Rogue::getHealth() {return health;}
void Rogue::setHealth(long int initHealth) {health = initHealth;}
void Rogue::healthChange(long int vDelta) {health += vDelta;}
coordinateYX Rogue::getHeroPosition() {return heroPosition;}
void Rogue::setHeroPosition(coordinateYX hPos)
{
heroPosition.y = hPos.y;
heroPosition.x = hPos.x;
}
In my main.cpp, I am trying to store the current cursor position into an instantiation of Rogue:
Rogue Hero;
getyx(stdscr, Hero.getHeroPosition().y, Hero.getHeroPosition().x);
But I always get an error:
using temporary as lvalue [-fpermissive]
It also shows this below as part of the error which is in the <curses.h> file
#define getyx(w, y, x) (y = getcury(w), x = getcurx(w))
Although I can simply store these values in another struct initialized in main.cpp, how can I store the x and y positions directly in the class data members?
Thank you.
The quickest solution would be to change getHeroPosition to return a reference instead of value:
coordinateYX& Rogue::getHeroPosition() {return heroPosition;}
The problem is here you are trying to assign to the Rogue position:
getyx(stdscr, Hero.getHeroPosition().y, Hero.getHeroPosition().x);
This is equivalent to:
Hero.getHeroPosition().y = getcury(stdscr);
Hero.getHeroPosition().x = getcurx(stdscr);
But getHeroPosition returns the position by value (it returns a copy, an rvalue). If you assign a value to that temporary copy it will just be lost. The solution is to assign to a reference to the actual Rogue position (an lvalue).
Alternatively, you can use your existing setPosition function:
coordinateYX position;
getyx(stdscr, position.X, position.Y);
Hero.setPosition(position);