Constructors accessing private data - c++

Still new to C++ and I'm trying to understand accessing private data, using constructors. How would I display the values of the data members of myClass? Any help would be great. Thanks
class NumberClass
{
public:
void func(); // assigns numeric constants to nNum and fNum
void print() const; //displays the values of nNum and fNum
NumberClass();
NumberClass(int, float);
private:
int nNum;
float fNum;
};
int main()
{
NumberClass myClass;
//display values here
return 0;
}

By the looks of your interface, your professor probably wants you to implement print() to print the members, and then call that method on your object.

You could implement print(), and call it with a instance of NumberClass. Like
NumberClass obj;
...
obj.print()

You could write get methods for the class which is a good way to print it.
class NumberClass
{
public:
void func(); // assigns numeric constants to nNum and fNum
void print() const; //displays the values of nNum and fNum
NumberClass();
NumberClass(int, float);
private:
int nNum;
float fNum;
public int getNum(){
return nNum;
}
public float getNum(){
return fNum;
}
};
int main()
{
NumberClass myClass;
//display values here
cout<<myClass.getNum();
return 0;
}
Could be the example but I didint checked so you can fixed the little issues.

Related

Get and Set function c++

i just wanted to know if someone could help me about my code,i am a little confused to why it is not working like i want it to maybe i am misunderstanding something...The point of the program is to write a class with two functions to set and get a number but later on the main part of the code i have wanted it to print out a 2.52 number not just the number 2.Thank you if anyone helps :) .
#include <iostream>
#include<conio.h>
using namespace std;
class Class
{
public:
void Set(float x)
{
number = x;
}
int Get()
{
return number;
}
private:
float number;
};
int main()
{
Class object;
object.Set(2.52);
cout << "The number is: " << object.Get();
return 0;
}
First of all, you return an int from Get() so number will be converted in an int.
You should also make Get() const since it's will not change anything in the Class object when you call the function. Making it const makes it possible to pass instances of Class to functions taking a Class by const&:
#include <iostream>
class Class
{
public:
void Set(float x)
{
number = x;
}
float Get() const // returning float and added const
{
return number;
}
private:
float number;
};
void tester(const Class& obj) // a function taking a Class by const reference:
{
std::cout << "The number is: " << obj.Get() << '\n';
}
int main()
{
Class object;
object.Set(2.52);
tester(object);
}
Without the added const compilation would fail.
you can change get method type(float) like that
class Class
{
public:
void Set(float x)
{
number = x;
}
float Get()
{
return number;
}
private:
float number;
};
int main()
{
Class object;
object.Set(2.52);
cout << "The number is: " << object.Get();
return 0;
}

class inheritance and using setters and getters

Here I've made a derived class called Essay, from the base class GradedActivity. I've made an object of the Essay class in main called object. When I wrote object.setGrammar(grammarPts) in main(), I'd hoped to feed what the score is to be held in the variable grammar in the setGrammar() function. What am I doing wrong? Thanks!
I get one error:
99 8 F:\lab6part3.cpp [Error] request for member 'setGrammar' in 'object', which is of non-class type 'Essay(float, float, float, float)'
#include <iostream>
using namespace std;
//class gradedactivity (page 900)
class GradedActivity
{
protected:
double score;
public:
//default constructor
GradedActivity()
{
score = 0.0;
}
//parameterized constructor
GradedActivity(double s)
{
score = s;
}
setScore(double s)
{
score = s;
}
double getScore() const
{
return score;
}
char getLetterGrade() const;
};
class Essay : public GradedActivity
{
private:
float grammar;
float spelling;
float length;
float content;
public:
Essay(float g, float s, float l, float c)
{
setGrammar(g);
setSpelling(s);
setLength(l);
setContent(c);
}
void setGrammar(float);
float getGrammar();
void setSpelling(float);
float getSpelling();
void setLength(float);
float getLength();
void setContent(float);
float getContent();
};
void Essay::setGrammar(float g)
{
grammar = g;
}
float Essay::getGrammar() {return grammar;}
void Essay::setSpelling(float s)
{
spelling = s;
}
float Essay::getSpelling() {return spelling;}
void Essay::setLength(float l)
{
length = l;
}
float Essay::getLength() {return length;}
void Essay::setContent(float c)
{
content = c;
}
float Essay::getContent() {return content;}
int main()
{
float grammarPts;
cout << "How many points, out of 30, did the student get for grammar?";
cin >> grammarPts;
Essay object;
object.setGrammar(grammarPts);
return 0;
}
This could just be because you never defined a default constructor for Essay.
Anyway, I defined a default constructor and your code runs fine so that might be the issue. https://ideone.com/yNxV8N

How to start with Classes in c++

I at classes and objects of C++, where i am facing difficulties to understand the concept of deceleration of a class, for which i have make a little program which is not compiling, anybody will guide me?
#include <iostream>
using namespace std;
class myClass{
friend increment(myClass, int);
private:
int topSecret;
public:
myClass(){
topSecret = 100;
}
void display(){
cout<<"The value of top Secter is"<<topSecret;
}
};
void increment(myClass A, int i){
A.topSecret += i;
}
int main() {
myClass x;
x.display();
increment(x,10);
x.display();
}
Change
friend increment(myClass, int);
to
friend void increment(myClass &, int);
That should fix your compilation errors.
To modify the original object passed to a function, declare the function to take a reference:
void increment(myClass A, int i){
to
void increment(myClass &A, int i){
Arun's answer shows you how to fix your compilation error, but this is not how you should design a class. Defining non-member friend functions to access your internal data will often lead to maintenance issues and bugs. You would be better off either declaring increment as a public member function, or defining getter and setters for your class:
class myClass{
private:
int topSecret;
public:
//use initialization list instead of setting in constructor body
myClass() : topSecret(100) {}
//getter, note the const
int GetTopSecret() const { return topSecret; }
//setter, non-const
void SetTopSecret(int x) { topSecret = x; }
//member version
void increment (int i) { topSecret += i; }
};
//non-member version with setter
//note the reference param, you were missing this
void increment(myClass &A, int i){
A.SetTopSecret(A.GetTopSecret() + i);
}
Add void bebore increment in class definition as Arun A.S said.
You can't change A.topSecret in increment function because you take object by value, so you just change temporary object, use instead void increment(myClass &A, int i)

Getting one private member from one class to another

So, I have an algorithm that takes a few sensors, scales them to a temperature and puts the temps in a global data store. However, sensor class A does more calculations that Class B needs. I can't put the new calcs in the data store, and i don't want to include class A inside class B just to get one piece of data with a getter.
Class A
{
private:
float x[4];
float y[4];
public:
//Scaling functions, etc...
}
Class B
{
private:
float c[4];
public:
//Scaling functions etc...
}
What would be the best way to get x[4] passed to class B to put in c[4]? The real classes have much more going on, this is about as simple as I think I can make. x[4] has data that needs to be used in class B.
class A
{
private:
float x[4];
float y[4];
public:
float* getXs()
{
return x;
}
}
class B
{
private:
float c[4];
public:
//Scaling functions etc...
void setXs(float *x)
{
for (int i=0;i<4;i++)
c[i] = x[i];
}
}
Well, you could use friends, if you're not willing to write accessors:
http://en.wikipedia.org/wiki/Friend_class
Some would argue this breaks encapsulation, and that a getter would be the preferred approach.
Use a getter of x[4] on an instance of A when calling the constructor of B.
#include <string.h>
class A
{
private:
float x[4];
float y[4];
public:
float const *xArray() const
{
return x;
}
};
class B
{
private:
float c[4];
public:
void setCArray(float const arr[4])
{
memcpy(c, arr, 4 * sizeof(int));
}
};
int main()
{
A a;
B b;
b.setCArray(a.xArray());
}
There are number of ways. The best depends on Your criteria.
If time is not crucial for you I would be simple and use copy constructor:
Class A
{
private:
float x[4];
float y[4];
public:
const float& X(int i) { return x[i]; }
}
Class B
{
private:
float c[4];
public:
B( const A& a ) {
for( k = 0; k < 4; k++ )
c[k] = a.X(k);
}
}
If time is crucial you can consider to use pointers copy. But be Very accurate with it:
Class A
{
private:
friend B;
float x[4];
float y[4];
public:
...
}
Class B
{
private:
const float* const c;
public:
B( const A& a ):c(a.x){}
// use c like c[4], but don't change it.
}

Making a structure in class

I am making my first steps in learning OOP . And here is the first problem which I can't solve.
The max function in this class should return the maximum of two numbers . I want to keep the numbers in the private scope and the functions in the public scope . But when I want to use variables from struct data{} in the public scope the compiler says that the variables are not declared . Please tell me why I get these errors .
class myclass{
private:
struct data{
int q ;
int w;
};
public:
void get(int a, int b){
struct data = {a , b}; // here I want to pass the variables to data struct
}
int max (){ // this function returns the biggest number
if(q>w)
return q;
else
return w;
}
};
struct data{
int q ;
int w;
};
only declares a type, not an object, so there are no q and w members anywhere inside your class instances. You need the declare an instance of the struct:
struct {
int q;
int w;
} data;
Then, you can write max as:
int max()
{
if (data.q > data.w)
return data.q;
else
return data.w;
}
(I've no idea what your get method is supposed to do, so I have no replacement for that.)
In C++ "class" and "struct" are close to being synonymous (the same thing). The ONLY difference is that a "struct" defaults to being "public" accessibility while a "class" defaults to private.
Once you understand this, it should become obvious that what you are doing is defining a sub-type within your class.
class myclass {
private: // <- not required, you already said that by saying "class".
struct data {
// <-- this is a class definition with "public:" just here.
...
};
};
C++ allows you to nest class/structure definitions so that you can, for example, create structures that marshal parameters or return values.
class Database {
class Result { ... };
};
...
class Exam {
class Result { ... };
};
These two result classes avoid namespace collision, by being Database::Result and Exam::Result instead of just "Result".
However - these are only definitions. They do not - as shown - have any effect on the outlying class, that is: they aren't being used to add a member to the class.
Your code:
class myclass{
private:
struct data{ // <-- this is a TYPE declaration, struct myclass::data
int q ; //
int w; //
}; // <-- no member name here so does not affect myclass itself.
public:
void get(int a, int b){
struct data = {a , b}; // here I want to pass the variables to data struct
}
int max (){ // this function returns the biggest number
if(q>w)
return q;
else
return w;
}
};
Declares a type "myclass::data" but does not add a member of type "myclass::data" to the class. The line "struct data = " is illegal, you're trying to assign values to a TYPE.
It should probably be written as
class MyClass {
int m_q;
int m_w;
public:
void set(int q, int w) {
m_q = q;
m_w = w;
}
int max() const {
return (m_q > m_w) ? m_q : m_w;
// or #include <algorithm> and return std::max(m_q, m_w);
}
};
You only need to hoist q & w into a struct if you are going to reuse that structural definition outside the confines of the class, e.g. in derived or parallel classes where you may want to add more of the same type of thing, in which case, you could perhaps do the following, but if you do it this exact way you'll eventually kick yourself for breaking encapsulation:
class MyClass {
public:
struct Data {
int m_q;
int m_w;
};
private:
Data m_data;
void set(int q, int w) {
m_data.m_q = q;
m_data.m_w = w;
}
int max() const {
return (m_data.m_q > m_data.m_w) ? m_data.m_q : m_data.m_w;
}
};
A better way, if this coupling of members needs to be externally visible to some degree would be:
class MyClass {
public:
class Data {
int m_q;
int m_w;
public:
Data() : m_q(0), m_w(0) {}
Data(int q, int w) : m_q(0), m_w(0) {}
void set(int q, int w) {
m_q = w;
m_w = w;
}
int q() const { return m_q; }
int w() const { return m_w; }
int max() const { return (m_q > m_w) ? m_q : m_w;
};
private:
Data m_data;
public:
MyClass() : m_data() {} // or = default
MyClass(int q, int w) : m_data(q, w) {}
MyClass(const Data& data) : m_data(data) {}
// Read-only access
const Data& data() const { return m_data; }
// To allow write access, e.g. for set:
Data& data() { return m_data; }
};
It's kinda overkill for such a simple case, but welcome to C++: the boilerplate language.
You have defined the structure but there is no object of that type. You should declare an object and you will not get any error.
class myclass{
private:
struct data{
int q ;
int w;
}var;
public:
void get(int a, int b){
var .q= a;
var.w=b; // here I want to pass the variables to data struct
}
int max (){ // this function returns the biggest number
if(var.q>var.w)
return var.q;
else
return var.w;
}
};