sixtyTonneAngel
sixtyTonneAngel

Reputation: 901

C++ Class - using public variables and defining member functions outside class

I have a defined a class C. I want to write all member functions in a file named C.cpp which I know how to. What I don't know is the following:

  1. How to define one function, f, in the main? I tried:

    C::f(arguments){
    /*function definition*/}
    
    int main(){ /*code in main*/
    }
    
  2. How to access and change a public member variable 'x' in my main after I define an object P of class C, without defining an explicit function for that? I'm looking to do something like

    P.x = 5.67;
    

Upvotes: 0

Views: 14499

Answers (1)

A.S.H
A.S.H

Reputation: 29332

For 1., If f is not declared in the class C (that is, in C.h), you cannot. you cannot add a function to a class dynamically.

Also if is is declared in C.h and also defined in C.cpp, then you are attempting to duplicate its definition, you cannot as well.

If it is declared in C.h and not defined in C.cpp, you can define it here in the main's file, BUT this is not recommended (bad practice). Better put all the class's definitions of methods in its .cpp file.

For 2, You can modify an attribute for an object of class C if that member was declared in the public section of the class:

class C {
... // private members
public: // public section
    double x;
    ... // other public members, methods or attributes
};

In this case you can, in main:

C P;
P.x = 5.67;

Upvotes: 3

Related Questions