Making a custom class in c++ with constructor values - c++

I'm still learning c++ and have a lot more experience with Java. In Java, creating a class can be as simple as this:
public class vertex
{
public double x, y, z;
public boolean eliminated = true;
public vertex(double x, double y, double z)
{
//vertex constructor
}
}
I'm trying to do something pretty much identical in C++, save for built in "get" functions for returning the values that should be set when creating an instance of the class, and want to know if my syntax is correct. Here is the class:
#include <iostream>
#include <stdlib.h>
using namespace std;
class Vertex // Standard way of defining the class
{
public:
// This means that all of the functions below this(and any variables) are accessible to the rest of the program.
Vertex(double x, double y, double z);
//constructor
double getX();
double getY();
double getZ();
double x;
double y;
double z;
};
double Vertex:: getX()
{
return x;
}
I would also like advice on creating a class that has instances of custom classes like the one aboce within them.

public class vertex
{
public double x, y, z;
public boolean eliminated = true;
public vertex(double x, double y, double z)
{
//vertex constructor
}
}
To mimic this Java class as simply and as exactly as possible in C++ you would do this:
struct vertex{
double x, y, z;
bool eliminated = true;
vertex(double x, double y, double z){
//vertex constructor
}
};
Remarkably similar right? Note that the eliminated member is default initiated, which is new to C++11, so make sure you have an up to date compiler.
struct is used instead of class because all of your members are public anyway. You could also use class and the public: access specifier.
You do not need access methods (getters) because everything is public already, as in your Java class.
You don't need any includes in for your vertex class definitions and you definitely should NOT put a using declaration any header files.
To mimic Java method parameter passing you pass copies for primitives and non-const pointers (not references) for object instance parameters.
edit - fixed the silly issues that I missed and that the human compilers below spotted :)

This might help you out:
Vector3.h
#ifndef VECTOR3_H
#define VECTOR3_H
namespace myNamespace { // Add This Because Many Libraries may define a Vector3 Object
class Vector3 {
union {
float m_f3[3];
struct {
float m_fx;
float m_fy;
float m_fz;
};
};
inline Vector3();
inline Vector3( float x, float y, float z );
inline Vector3( float *pfv );
~Vector3();
// Add Your inline overloaded operators & inline function declarations here.
};
#include "Vector3.inl"
} // namespace myNameSpace
#endif // VECTOR3_H
Vector3.inl
// ------------------------------------------------------
// Vector3() - Default Constructor Sets All Values To 0
inline Vector3::Vector3() :
m_fx( 0 ),
m_fy( 0 ),
m_fz( 0 ) {
} // Vector3
// ------------------------------------------------------
// Vector3() - Takes (x,y,z) Parameters
inline Vector3::Vector3( float x, float y, float z ) :
m_fx( x ),
m_fy( y ),
m_fz( z ) {
} // Vector3
// ------------------------------------------------------
// Vector3() - Takes A Pointer To Type
inline Vector3::Vector3( float *pfv ) :
m_fx( pfv[0] ),
m_fy( pfv[1] ),
m_fz( pfv[2] ) {
} // Vector3
Vector3.cpp
#include "Vector3.h"
namespace myNamespace {
// ----------------------------------------------
// ~Vector3() - Default Destructor - Does Nothing
// Only Defined Here So That There Is Some Type Of Translation
// Unit In The Object File Generated When Compiling
Vector3::~Vector3() {
} // ~Vector3
} // namespace myNamespace
To use this:
main.cpp
#include <iostream>
#include "Vector3.h"
int main() {
using namespace myNamespace; // Forgot to add this line here.
Vector3 v1;
std::cout << "Default Constructor Used: " << std::endl;
std::cout << "v1 = ( " << v1.m_fx << ", "
<< v1.m_fy << ", "
<< v1.m_fz << " )" << std::endl;
// Or This Way Works Too
std::cout << "v1 = ( " << v1.m_f3[0] << ", "
<< v1.m_f3[1] << ", "
<< v1.m_f3[2] << " )" << std::endl;
Vector3 v2( 2.2f, 3.3f. 4.4f );
std::cout << "2nd Constructor Used: " << std::endl;
std::cout << "v2 = ( " << v2.m_f3[0] << ", "
<< v2.m_f3[1] << ", "
<< v2.m_f3[2] << " )" << std::endl;
float f3[3] = { 4.5f, 6.7f, 8.9f };
Vector3 v3( f3 );
std::cout << "3rd Constructor Used: " << std::endl;
std::cout << "v3 = ( " << v3.m_fx << ", "
<< v3.m_f3[1] << ", "
<< v3.m_fz << " )" << std::endl;
} // main
EDIT:
If you want a have a class that includes instances of another user define class then it is as simple as this:
SomeClass.h
#ifndef SOME_CLASS_H
#define SOME_CLASS_H
namespace myNamespace {
class Vector3;
class SomeClass {
private:
Vector3 m_currentPosition;
Vector3 m_velocity;
Vector3 m_finalPosition;
public:
SomeClass( Vector3 initialPosition, Vector3 currentVelocity );
Vector3 getFinalPosition() const;
private:
void calculateFinalPosition();
};
} // namespace myNamespace
SomeClass.cpp
#include "SomeClass.h"
#include "Vector3.h"
namespace myNamespace {
SomeClass::SomeClass( Vector3 initialPosition, Vector3 currentVelocity ) :
m_currentPosition( initialPosition ),
m_velocity( currentVelocity ) {
calculateFinalPosition();
}
Vector3 SomeClass::getFinalPosition() const {
return m_finalPosition;
} // getFinalPosition
void SomeClass::calculateFinalPosition() {
// Perform The Appropriate Calculation Here To Find The Final Position
} // calculateFinalPosition
} // namespace myNamespace
However for this to work; this would require the Vector3 to have the overloaded operators, functions such as cross, dot etc., to be defined.

Related

How do I call a function from a given class in a different class

I want to declare a function in one class and run it in a different one.Below is the implementation of my class
#include <iostream>
#include <cstdlib>
#include <math.h>
using namespace std;
int myNo = 1 + rand () % 10;
class Point {
protected: int x; int y;
Point() {
x = myNo;
y = myNo;
}
float distanceBetweenMeAndAnotherPoint (Point anotherPoint){
float xyz = sqrt(pow((x-x),2) + pow((y-y),2));
return xyz;
}
};
class Circle : public Point {
private:
int radius;
Circle(int x, int y){
radius=myNo;
}
public:
printCircleInfo(){
cout << x << " " << y << " " << radius << " ";
return 1;
}Point Obj;
bool doIBumpIntoAnotherCircle (Circle anotherCircle){
if (radius + radius >=Obj.distanceBetweenMeAndAnotherPoint)
return true;
else
return false;
}
};
What should I replace Obj.distanceBetweenMeAndAnotherPoint with in order to call the function in this class?
Please provide an example in your answer. Thank you for your time.
You should use the parameter that you get, like this:
float distanceBetweenMeAndAnotherPoint (Point anotherPoint){
float dist = sqrt(pow((x-anotherPoint.x),2) + pow((y-anotherPoint.y),2));
return dist;
}
Also for the bump method, use the parameter that you get. And additionally simplify boolean return value, no need for the if-else. Resulting with something like:
bool doIBumpIntoAnotherCircle (Circle anotherCircle) {
return distanceBetweenMeAndAnotherPoint(anotherCircle)
<= (radius + anotherCircle.radius);
}
Note also that constructors should usually (though not necessarily) be public. In your case, the ctor of both classes, Point and Circle, should most likely be public and not private or protected to allow creation of objects of these types in your main.

How to make object of a class with parameterized constructor in other class?

I want to make an object of DataArea class in Area class and initialize data in main function. But the only way my code works is by initializing data in Area class.
Also, I do not know if I have made the object correctly or not. Please guide me. My code is below:
#include<iostream>
using namespace std;
class DataArea
{
public:
int radius, length, width, base, heigth;
DataArea(int l, int w, int b, int h, int r)
{
length = l;
width = w;
radius = r;
heigth = h;
base = b;
}
};
class Area
{
public:
DataArea* s = new DataArea(3, 4, 5, 6, 7);
float AreaCirle()
{
return 3.142 * s->radius * s->radius;
}
float AreaRectangle()
{
return s->length * s->width;
}
float AreaTraingle()
{
return (s->base * s->heigth) / 2;
}
};
class print_data : public Area
{
public:
void print()
{
cout << "Area of Circle is: " << AreaCirle() << endl;
cout << "Area of Rectangle is: " << AreaRectangle() << endl;
cout << "Area of Traingle is: " << AreaTraingle() << endl;
}
};
int main()
{
//DataArea da(3, 4, 5, 6, 7);
print_data m;
m.print();
}
Your DataArea is basically absolute if you do not use it outside of Area class. Similarly, print_data class can be replaced by an operator<< overload.
Following is the updated code, in which the comments will guide you through.
#include <iostream>
// DataArea (optionally) can be the part of Area class
struct DataArea /* final */
{
float length, width, base, height, radius;
DataArea(float l, float w, float b, float h, float r)
: length{ l } // use member initializer lists to initlize the members
, width{ w }
, base{ b }
, height{ h }
, radius{ r }
{}
};
class Area /* final */
{
DataArea mDataArea; // DataArea as member
public:
// provide a constructor which initialize the `DataArea` member
Area(float l, float w, float b, float h, float r)
: mDataArea{ l, w, b, h, r } // member initializer
{}
// camelCase naming for the functions and variables
// mark it as const as the function does not change the member
float areaCirle() const /* noexcept */
{
return 3.142f * mDataArea.radius * mDataArea.radius;
}
float areaRectangle() const /* noexcept */
{
return mDataArea.length * mDataArea.width;
}
float areaTraingle() const /* noexcept */
{
return (mDataArea.base * mDataArea.height) / 2.f;
}
// provide a operator<< for printing the results
friend std::ostream& operator<<(std::ostream& out, const Area& areaObject) /* noexcept */;
};
std::ostream& operator<<(std::ostream& out, const Area& areaObject) /* noexcept */
{
out << "Area of Circle is: " << areaObject.areaCirle() << "\n";
out << "Area of Rectangle is: " << areaObject.areaRectangle() << "\n";
out << "Area of Traingle is: " << areaObject.areaTraingle() << "\n";
return out;
}
int main()
{
// now construct the Area object like this
Area obj{ 3, 4, 5, 6, 7 };
// simply print the result which uses the operator<< overload of the Area class
std::cout << obj;
}
Output:
Area of Circle is: 153.958
Area of Rectangle is: 12
Area of Traingle is: 15
It seems to me that Area class is surplus for what you are trying to achieve. You should probably put methods directly in DataArea class. Then you can create as many of DataArea objects as you like...
Like this:
class DataArea
{
public:
int radius, length, width, base, heigth;
DataArea(int l , int w , int b , int h , int r )
{
length = l;
width = w;
radius = r;
heigth = h;
base = b;
}
float AreaCirle()
{
return 3.142 * radius * radius;
}
float AreaRectangle()
{
return length * width ;
}
float AreaTraingle()
{
return (base * heigth)/2;
}
};
int main(int argc, char **argv)
{
DataArea area1 (1,2,3,4,5);
DataArea area2 (8,2,3,4,5);
std::cout << area1.AreaCirle() << std::endl;
std::cout << area2.AreaCirle() << std::endl;
}
The reason why you are probably having trouble to understand the concept:
You're defining a class and instantiating an object. Sometimes these terms are used interchangeably, but in this case, this is an important distinction.
If you would like for your methods to operate on some other class, that you should make methods that accept that class as an argument. Otherwise, it is unnecessary complex.

Creating a Class with 2 double values in C++

In C++ I am trying to create a class Point2D that contains two double values. All data members and functions should be public.
For Public Members there should be
double x
double y
For Constructors
the default constructor should initialize x and y to 0.0
Point2D(double in_x, double in_y)
sets x and y to in_x and in_y
For non-member Functions
void GetResult(Point2D p1, Point2D p2)
Prints x and y values for both
This is the code I have so far, can somebody please point out my errors?
Point2D.h
#ifndef POINT2D_H
#define POINT2D_H
class Point2D
{
public:
double x;
double y;
Point2D();
Point2D(double,double);
};
void GetResult(Point2D, Point2D);
#endif
Point2D.cpp
#include "Point2D.h"
#include <iostream>
using namespace std;
Point2D::Point2D()
{
x = 0.0;
y = 0.0;
}
Point2D::P1(double in_x, double in_y)
{
x = in_x;
y = in_y;
}
Point2D::P2(double in_x, double in_y)
{
x = in_x;
y = in_y;
}
void GetResult(Point2D P1, Point2D P2)
{
cout << P1.x << " " << P1.y << endl;
cout << P2.x << " " << P2.y << endl;
}
TestCheckPoint1.cpp
#include <iostream>
#include "Point2D.h"
using namespace std;
int main()
{
Point2D Point1;
Point1.x = 1.0;
Point1.y= 2.0;
Point2D Point2;
Point2.x= 1.0;
Point1.y= 2.0;
GetResult(Point1, Point2);
}
You are close, but it is clear you have a bit of misunderstanding about overloaded constructors and declaring instances of your class. For starters, you don't need the functions:
Point2D::P1(double in_x, double in_y)
{
x = in_x;
y = in_y;
}
Point2D::P2(double in_x, double in_y)
{
x = in_x;
y = in_y;
}
You simply need a single constructor for your Point2D class that takes two double values, e.g.
Point2D::Point2D(double in_x, double in_y)
{
x = in_x;
y = in_y;
}
Then in main() you need to declare and initialize default constuct two-instances of class Point2D providing the desired values to x and y before calling GetResult, e.g.
#include <iostream>
#include "Point2D.h"
using namespace std;
int main()
{
Point2D Point1 (1.0, 2.0);
Point2D Point2 (1.0, 2.0);
GetResult(Point1, Point2);
}
(note: You can provide an initializer lists that allow initialization of the class members, see Constructors and member initializer lists. You could provide an initializer list for your constructor with, e.g. Point2D() : x(0), y(0) {}; and the overload Point2D(double, double);. Your constructor definition would simply be Point2D::Point2D(double in_x, double in_y) : x(in_x), y(in_y) {} and the compiler would initialize x, y to 0, 0 if created with Point2D Point1; or set x, y to values provided as Point2D Point2 (1.0, 2.0);)
You did a very good job including the Header Guards around the contents of Point2D.h to prevent multiple inclusion if included in more than one file. The complete header and source files for Point2D could be:
#ifndef POINT2D_H
#define POINT2D_H
class Point2D
{
public:
double x;
double y;
Point2D();
Point2D(double,double);
};
void GetResult(Point2D, Point2D);
#endif
and
#include "Point2D.h"
#include <iostream>
using namespace std;
Point2D::Point2D()
{
x = 0.0;
y = 0.0;
}
Point2D::Point2D(double in_x, double in_y)
{
x = in_x;
y = in_y;
}
void GetResult(Point2D P1, Point2D P2)
{
cout << P1.x << " " << P1.y << endl;
cout << P2.x << " " << P2.y << endl;
}
Example Use/Output
Compiling and running would result in:
$ ./bin/TestCheckPoint1
1 2
1 2
Note: there is no need to using namespace std; in main() at all, and you really shouldn't include the entire standard namespace anywhere. Simply remove both calls and add std:: to your two cout calls and two calls to endl (or just use '\n' instead of std::endl;). See Why is “using namespace std;” considered bad practice?
Instead simply use:
void GetResult(Point2D P1, Point2D P2)
{
std::cout << P1.x << " " << P1.y << '\n';
std::cout << P2.x << " " << P2.y << '\n';
}
Look things over and let me know if you have further questions.

C++ providing default parameters to constructors

In the c++ class below, I've provided default parameters to the constructor in case the user does not provide one. However, when I for example Point2d1 first(1, 0); in main() I get an error of no matching function call. I expected the behavior to default the 3rd parameter to 0?
.h
#ifndef POINT2D1_H_
#define POINT2D1_H_
class Point2d1 {
private:
int m_Object_ID;
double m_x;
double m_y;
public:
//Point2d1(int nID);
Point2d1(int nID, double x, double y);
virtual ~Point2d1();
void print() const;
friend double distanceFrom(const Point2d1& D1, const Point2d1& D2);
};
#endif /* POINT2D1_H_ */
.cpp
Point2d1::Point2d1(int nID = 0, double x = 0.0, double y = 0.0) : m_Object_ID(nID), m_x(x), m_y(y)
{
std::cout << "Constructing Point2d object " << nID << '\n';
}
Point2d1::~Point2d1() {
std::cout << "Destructing Object" << '\n';
}
void Point2d1::print() const
{
std::cout << "Point2d(" << m_x << ", " << m_y << ")\n";
}
double distanceFrom(const Point2d1& D1, const Point2d1& D2)
{
double distance = sqrt((D1.m_x - D2.m_x)*(D1.m_x - D2.m_x) + (D1.m_y - D2.m_y)*(D1.m_y - D2.m_y));
return distance;
}
Declare the default arguments in the member function declartion inside the class definition in the header file. Otherwise other compilation units will not know about the default arguments.
For example
.h
#ifndef POINT2D1_H_
#define POINT2D1_H_
class Point2d1 {
//...
public:
//Point2d1(int nID);
Point2d1(int nID = 0, double x = 0.0, double y = 0.0);
//...
};
#endif /* POINT2D1_H_ */
and
.cpp
Point2d1::Point2d1(int nID, double x, double y) : m_Object_ID(nID), m_x(x), m_y(y)
{
std::cout << "Constructing Point2d object " << nID << '\n';
}

Undefined reference to my classes? C++ Beginner

To get a bit of practice with OOP i'm trying to make a Point class (has 2 ints, x & y) and a Line class (has 2 Points).
Now when i go to build my main.cpp i get errors like..
"undefined reference to `Point::Point(float, float)' " and
" undefined reference to `Line::Line(Point, Point)'"
At a loss as to why, perhaps you could take a brief look at my files? It'd be much appreciated!
Main.cpp
#include "Point.hpp"
#include "Line.hpp"
#include <iostream>
using namespace std;
int main()
{
Point p1(2.0f, 8.0f); // should default to (0, 0) as specified
Point p2(4.0f, 10.0f); // should override default
p1.setX(17);
if ( p1.atOrigin() && p2.atOrigin() )
cout << "Both points are at origin!" << endl;
else
{
cout << "p1 = ( " << p1.getX() << " , " << p1.getY() << " )" <<endl;
cout << "p2 = ( " << p2.getX() << " , " << p2.getY() << " )" <<endl;
}
Line line(p1, p2);
Point midpoint = line.midpoint();
cout << "p1 = ( " << midpoint.getX() << " , " << midpoint.getY() << " )" <<endl;
return 0;
}
Line.hpp
#ifndef _LINE_HPP_
#define _LINE_HPP_
#include "Point.hpp"
class Line{
public:
Line(Point p1, Point p2);
//void setp1(Point p1);
//void setp2(Point p2);
//Point getp1 finish
Point midpoint();
int length();
private:
int _length;
Point _midpoint;
Point _p1, _p2;
};
#endif
Line.cpp
#include "Line.hpp"
#include <math.h>
Line::Line(Point p1, Point p2) : _p1(p1), _p2(p2)
{
}
Point Line::midpoint()
{
_midpoint.setX() = (_p1.getX()+ _p2.getX()) /2;
_midpoint.setY() = (_p1.getY()+ _p2.getY()) /2;
}
int Line::length()
{
//a^2 + b^2 = c^2
_length = sqrt( ( (pow( _p2.getX() - _p1.getX(), 2 ))
+(pow( _p2.getY() - _p1.getY(), 2 )) ) );
}
Point.hpp
#ifndef _POINT_HPP_
#define _POINT_HPP_
class Point {
public:
Point( float x = 0, float y = 0);
float getX() const;
float getY() const;
void setX(float x = 0);
void setY(float y = 0);
void setXY(float x = 0, float y = 0);
bool atOrigin() const;
private:
float _x, _y;
};
#endif
Point.cpp
#include "Point.hpp"
Point::Point(float x, float y) : _x(x), _y(y)
{
}
float Point::getX() const
{
return _x;
}
float Point::getY() const
{
return _y;
}
void Point::setX(float x)
{
//if (x >= 0 &&
_x = x;
}
void Point::setY(float y)
{
//might want to check
_y = y;
}
void Point::setXY(float x , float y )
{
setX(x);
setY(y);
}
bool Point::atOrigin() const
{
if ( _x == 0 && _y == 0)
return true;
return false;
}
In C++, not only do you have to compile main.cpp, but you also have to compile your Line.cpp and Point.cpp files. Then, when you have them all compiled into object files, you must link the object files together. This is handled automatically by some other languages such as Java.
The exact instructions on how to do this will depend on which development environment you are using.
Your Point.cpp isn't being compiled or given to the linker, try including it in your build.