Bilal
Bilal

Reputation: 31

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();

     }

Upvotes: 0

Views: 88

Answers (3)

Arun A S
Arun A S

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

Kotu
Kotu

Reputation: 1102

  1. Add void bebore increment in class definition as Arun A.S said.
  2. 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)

Upvotes: 1

TartanLlama
TartanLlama

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

Related Questions