Reputation: 31
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();
}
Upvotes: 0
Views: 88
Reputation: 7026
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){
Upvotes: 2
Reputation: 1102
Upvotes: 1
Reputation: 65770
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);
}
Upvotes: 2