getting value from another function and class c++ - c++

Sorry guys I'm new to C++ and I have this silly question to ask. how to I retrieve the value of civIndex from LocationData computeCivIndex function to PointTwoD class. does the GET function help in this situation?
LocationData.h
class LocationData
{
private:
string sunType;
int noOfEarthLikePlanets, noOfEarthLikeMoons;
float aveParticulateDensity, avePlasmaDensity;
static float civIndex;
public:
LocationData(); //default constructor
LocationData(string, int, int, float, float); // no default constructor
void setLocationData(string, int, int, float, float);
void displaydata();
static float computeCivIndex(string st, int earth, int moons, float particle, float plasma);
};
locationdataimp.cpp
float LocationData::civIndex = 0;
//convert sunType to sunTypePercentage
float LocationData::computeCivIndex(string st, int earth, int moons, float particle, float plasma)
{
float sunTypePercent;
if(st == "Type 0")
{
sunTypePercent = 80.0;
}
else if(st == "Type B")
{
sunTypePercent = 45.0;
}
else if(st == "Type A")
{
sunTypePercent = 60.0;
}
else if(st == "Type F")
{
sunTypePercent = 75.0;
}
else if(st == "Type G")
{
sunTypePercent = 90.0;
}
else if(st == "Type K")
{
sunTypePercent = 80.0;
}
else if(st == "Type M")
{
sunTypePercent = 70.0;
}
// calculate CIV Value
float civNum,civNum1,civNum2,civNum3,civNum4,civNum5;
civNum1 = sunTypePercent / 100;
civNum2 = plasma + particle;
civNum3 = civNum2 / 200;
civNum4 = civNum1 - civNum3;
civNum5 = earth + moons;
civNum = civNum4 * civNum5;
civIndex = civNum;
//return civNum;
}
pointtwod.h file
class PointTwoD
{
private:
int xcord,ycord;
float civIndex;
LocationData locationdata;
public:
PointTwoD();
PointTwoD(int, int, string, int, int, float, float, float);
string toString();
void displayPointdata();
};
pointtwod.cpp
void PointTwoD::displayPointdata()
{
PointTwoD pointtwod;
LocationData locationdata;
cout << "X axis: " << xcord << endl;
cout << "Y axis: " << ycord << endl;
cout << "civ: " << locationdata.civIndex << endl;
//locationdata.displaydata();
}
so what should i include or what mistake have i made?

The declaration of static float LocationData::civIndex; means that civIndex is static and private(*) in LocationData.
(*) as the default access modifier
The private access means that you cannot access it directly via a variable of type LocationData if that class does not explicitly allow it. You have two options:
1) Provide a public getter function:
public static float LocationData::getCivIndex()
{
return civIndex;
}
Note: you will need to declare this function in the class definition as well:
class LocationData
{
// ...
public static float getCivIndex();
};
2) Make the access of civIndex in LocationData public.
The second option is not advised as that would allow any code to directly access and modify the value of civIndex, which can easily lead to errors (and errors of these types are hard to track down in a large project). Even if you need a setter function that only sets the passed-in value, it is advisable to declare the variable private as that forces other code to go through the public method, making it easier to identify what code is accessing the variable during debugging in case of an error.
You can use option 1) like this:
LocationData locationData;
locationdata.getCivIndex();
Or even without having a variable of type LocationData, as the variable is static in that class:
LocationData::getCivIndex();

computeCivIndex is a static member, so the correct syntax is:
cout << "civ: " << LocationData::civindex << endl;
However, your civindex variable is private, so you have to create a getter:
static float getCivIndex()
{
return civIndex;
}
cout << "civ: " << LocationData::getCivIndex() << endl;

You can not directly access locationdata.civIndex like you did. Why? Because you set civIndex as a private member of the LocationData class.
There are a few solutions depending on your needs:
Make civIndex a public member of LocationData
or
Create a getter method to provide civIndex such as
static float getCivIndex( )
{
return civIndex;
}
See:
C++ Public
C++ Protected
C++ Private

Related

Why it keeps return 0 when I enter the Data of The Heigh & Base

class BASIC_SHAPE (abstract)
class BASIC_SHAPE
{
public:
double GET_AREA(double _AREA) { AREA = _AREA; return AREA; }
virtual double CALC_AREA() = 0;
private:
double AREA =0;
};
Class CIRCLE
class CIRCLE:public BASIC_SHAPE
{
public:
CIRCLE() { RADIUS = 0; }
CIRCLE(double _RADIUS) { RADIUS = _RADIUS; }
virtual double CALC_AREA() {
double TEMP2 = 3.14 * pow(RADIUS, 2);
return GET_AREA(TEMP2);
}
private:
double RADIUS;
};
Class TRIANGLE
class TRIANGLE: BASIC_SHAPE
{
public:
TRIANGLE() { BASE = 0; HEIGHT = 0; }
TRIANGLE(double _BASE , double _HEIGHT) : BASE{_BASE}, HEIGHT{_HEIGHT} {}
virtual double CALC_AREA() {
double TEMP = 1 / 2 * (BASE * HEIGHT);
return GET_AREA(TEMP);
}
private:
double BASE, HEIGHT;
MAIN
CIRCLE SHAPE2;
TRIANGLE SHAPE3;
void main()
{
double RAD;
std::cout << "Enter a Circle Radius : ";
std::cin >> RAD;
CIRCLE SHAPE2(RAD);
CIRCLE* LEAD1 = new CIRCLE(RAD);
std::cout << "The Area is : " << LEAD1->CALC_AREA();
double BASE , HEIGHT;
std::cout << "\n\nEnter a Triangle Base : ";
std::cin >> BASE;
std::cout << "\nEnter a Triangle Height : ";
std::cin >> HEIGHT;
TRIANGLE SHAPE3(BASE, HEIGHT);
std::cout << SHAPE3.CALC_AREA();
}
it keeps returning zero when I input the BASE & HEIGHT
I have tried using arrow operator and get it with pointers put nothing worked , I,ve tried use pointers and other methods to give me the answer or the SUM of area but nothing happens . constructors or abstract Class are suspected but IDK how ??
As pointed out in the comments by #rturrado 1/2 is 0. 0 times anything is 0. either use 0.5 or 1/2.0*....
Also, why does your GET_AREA method set the area for the base class and return the set area? You need to have different getters and setters. Getter methods should not set and similarly setter methods should not get.
Also, it would be best if you get in the habit of using managed pointers.

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 use protected type inheritance in class?

#include<iostream>
#include<string>
#include<cmath>
using namespace std;
class Polygon {
public:
Polygon() {}
Polygon(int point, float length) {
mPoint = point;
mLength = length;
}
~Polygon() {}
virtual void calcPerimeter() {
cout << "Perimeter: " << mLength * mPoint;
}
virtual void calcArea() {
cout << "Area: " << sqrt(3) * pow(mLength, 2) / 4;
}
protected:
int mPoint;
double mLength;
};
class Rectangle : public Polygon {
public:
Rectangle() {}
Rectangle(int point, float length):mPoint(4), mLength(4 * length){}
~Rectangle() {}
void calcPerimeter() override {
cout << "Perimeter: " << mLength;
}
void calcArea() override {
cout << "Area: " << mLength * mLength;
}
};
int main() {
Polygon pol;
Rectangle rec(4, 10);
cout << "--- Polygon class---" << endl;
pol.calcPerimeter();
pol.calcArea();
cout << "---Rectangle class---" << endl;
rec.calcPerimeter();
rec.calcArea();
return 0;
}
I learned that if the protected part of the parent class is inherited as public, it is used like a private in the child class. By the way
Rectangle (int point, float length): mPoint (4), mLength (4 * length) {}
In this part, I get the error that mPoint and mLength are not non-static data members or the base class of Reactangle. If it's private, can't I use it like that in a class ??
If I'm misunderstanding, I hope you can tell me what's wrong. Thanks for reading.
You're right about being able to use protected data in the derived class. However, that's not the problem here.
In
Rectangle (int point, float length): mPoint (4), mLength (4 * length) {}
you are initializing the fields, and that can only be done once, in the initializer list of the constructor of the class in which they are declared (Polygon).
You could assign them in the body of the constructor:
Rectangle (int point, float length)
{
mPoint = 4;
mLength = 4 * length;
}
but better is just to call the base class constructor and let it do its job:
Rectangle (int point, float length):Polygon (4, 4 * length) {}
All of this begs the question why you're passing point to the Rectangle constructor when you don't use it.
Also, it's widely regarded as bad practice to have protected fields (protect methods are okay) because once they are protected they are accessible all the way down the inheritance hierarchy. Better to keep them private and provide protected set methods.

constant member in class

I have this class:
class model
{
private:
link_list list;
float parameter_B1;
float parameter_B0;
public:
model();
float getparameter_B1() const;
float getparameter_B0() const;
float predict();
void info();
};
In which float parameter_B1 and float parameter_B0 are constant , but in order to initialize them , I have to enter constructor body and read a file and using that file's data to find value of these two attributes, but once I set them ,they won't change again.(so I guess they are count as constant)
like this:
model::model()
{
char filename[300];
cout << "enter file name(path\\filname.txt):" << endl;
cin >> filename;
FILE* fp;
fp = fopen(filename, "r+");
float x, y;
if (fp == NULL)
{
cout << "Unable to open the file!" << endl;
exit(EXIT_FAILURE);
}
else
{
while (!feof(fp))
{
if (fscanf(fp, "%f\t%f", &x, &y) == 2)
{
Pair p(x, y);
list.insertNewNode(p);
}
}
}
Pair _average = list.average();
parameter_B1 = list.parameters1(_average);
parameter_B0 = list.parameters2(_average, parameter_B1);
}
but if I change my class to:
class model
{
private:
link_list list;
const float parameter_B1;
const float parameter_B0;
public:
model();
const float getparameter_B1() const;
const float getparameter_B0() const;
float predict();
void info();
};
I will receive these error "model::model()" provides no initialize for:
1. const member "model::parameter_B1"
2. const member "model::parameter_B0"
, but as you can see I can't use initializer list.
what should I do? is not declaring constant variable my only solution?
with delegating constructor, you might do
std::tuple<link_list, float, float> read_model_file()
{
char filename[300];
cout << "enter file name(path\\filname.txt):" << endl;
cin >> filename;
// ...
Pair _average = list.average();
parameter_B1 = list.parameters1(_average);
parameter_B0 = list.parameters2(_average, parameter_B1);
return {std::move(list), parameter_B0, parameter_B1};
}
class model
{
private:
link_list list;
const float parameter_B0;
const float parameter_B1;
public:
model() : model(read_model_file()) {}
model(std::tuple<link_list, float, float> t) :
list(std::get<0>(std::move(t))),
parameter_B0(std::get<1>(std::move(t))),
parameter_B1(std::get<2>(std::move(t)))
{}
// ...
};

linking error between two files c++

I have tried to call the class function computeCivIndex() from another class I have defined but it says that there was an undefined reference to LocationData::computeCivIndex(string, int, int, float, float) and a defined an unused funciton computeCivIndex(string int, int, float, float) in my LocationData.cpp
And I used g++ -Wall -W LocationData.h LocationData.cpp PointTwoD.h PointTwoD.cpp MissionPlan.cpp -o myProg.o to compile.
LocationData.h
static float computeCivIndex( string sunType_, int noOfEarthLikePlanets_, int noOfEarthLikeMoons_, float aveParticulateDensity_, float avePlasmaDensity_ ); /*calculate the possibility of life in the star system*/
};
LocationData.cpp
static float computeCivIndex( string sunType_, int noOfEarthLikePlanets_, int noOfEarthLikeMoons_, float aveParticulateDensity_, float avePlasmaDensity_ )
{
int sunTypePercent = 0;
float civIndex;
// convert string suntype to suntype percent
if (sunType_ == "Type O")
{
sunTypePercent = 30;
}
if (sunType_ == "Type B")
{
sunTypePercent = 45;
}
if (sunType_ == "Type A")
{
sunTypePercent = 60;
}
if (sunType_ == "Type F")
{
sunTypePercent = 75;
}
if (sunType_ == "Type G")
{
sunTypePercent = 90;
}
if (sunType_ == "Type K")
{
sunTypePercent = 80;
}
if (sunType_ == "Type M")
{
sunTypePercent = 70;
}
//compute the CivIndex
civIndex = ( (sunTypePercent/100) - (aveParticulateDensity_ + avePlasmaDensity_)/200 ) *
(noOfEarthLikePlanets_ + noOfEarthLikeMoons_);
return civIndex;
}
MissionPlan.cpp
float computeCivIndex[arraySize];
//compute civ index for all stored records
for (int i = 0; i < (entryNo+1); i++)
{
string suntype = locData[i].getSunType();
int earthlikeplanets = locData[i].getNoOfEarthLikePlanets();
int earthlikemoons = locData[i].getNoOfEarthLikeMoons();
float partdensity = locData[i].getAveParticulateDensity();
float plasdensity = locData[i].getAvePlasmaDensity();
locData[i].computeCivIndex(suntype,earthlikeplanets, earthlikemoons , partdensity, plasdensity);
point2d[i].setCivIndex(computeCivIndex[i]);
}
cout << "Computation Completed! ( " << entryNo <<" records were updated )" << endl;
That is because you have not implemented the function!
You need to qualify the function appropriately in the implementation to tell the compiler that you are actually implementing the class functions:
SomeClass.h:
class SomeClass
{
void someFunction();
static void someStaticFunction();
};
SomeClass.cpp:
void SomeClass::someFunction() { }
void SomeClass::someStaticFunction() { } // static must not be repeated!
If you do simply
void someFunction() { }
static void someStaticFunction() { }
you define two additional functions at namespace scope, not at class scope as you intended. By declaring them static, you additionally limit accessibility to from within the .cpp file they are defined in, so won't be found when compiling other .cpp files.
Be aware that static within a class has a completely different meaning than at global scope (and another different meaning within a function body) - Coming to that later. First, another error, though:
locData[i].computeCivIndex(suntype,earthlikeplanets, earthlikemoons , partdensity, plasdensity);
Via operator. (or operator-> on pointers), you can only call non-static functions (this is different from Java), static functions need to be called with class scope:
LocationData::computeCivIndex(suntype,earthlikeplanets, earthlikemoons, partdensity, plasdensity);
Meaning of static at different scopes:
class SomeClass
{
static void f(); // static class function as you know
};
static void anotherF(); // free/global function - static limits accessibility!
void yetAnotherF()
{
static int n = 0; // see below
}
static void anotherF(); is the C way to limit acessibility - the C++ variant of is placing the function into an anonymous namespace:
namespace
{
void anotherF() { }
}
Finally: static within functions: This way, you declare some kind of global variable that is only accessible from within the function. It is initialised only the first time you call the function, and the previous value of will be available on all subsequent calls:
void f()
{
static int x = 0;
printf("%d ", ++x);
}
int main()
{
f();
f();
f();
return 0;
}
Output will be: 1 2 3.
More details you find here.