Sound designer/Game Developer based in South Yorkshire, UK

Report RSS const in c++

Posted by on

c++:-

#include <iostream>
using namespace std;

class testclass
{
    public:
    int t;
    int g;

    void cannotbreakme () const;//const means that the member variables of an instance of this class cannot be altered by this function.
};

    void testclass::cannotbreakme() const
    {
        //can't alter the value of t, just read it.
        cout << t;
    }

void copyit (testclass theclass)
{
    //will copy all of the data from theclass, so slow
    cout << theclass.t;
}


void nocons (testclass &amp;theclass)
{
    //passed by reference - fast, but can alter the values in the class
    theclass.t = 7;
}

void withcons (const testclass &amp;theclass)
{
    //passed by reference again, so fast - cannot alter any of it, just read
    cout << theclass.t;
}




int main ()
{

    testclass iamtestclass;

    copyit(iamtestclass);

    nocons(iamtestclass);

    cout << iamtestclass.t;

    withcons(iamtestclass);


    int const * valuepointedatcannotbechanged;//or const int *

    //int * const locationpointedtocannotbechanged;

    //int const * const neithercanbechanged;


    return 0;
}

int const * getvalue()
{
    static int send = 7;

    return &amp;send;
}

//values returned from functions can also be const - here the static int send within this function cannot be altered using the returned pointer.

also, this will not compile

void whatnow (const testclass *theclass)
{
    theclass->t = 7;
}

which is good!


I should look at unity now - try to do a gameobject.localposition = existingVector3, see what happens.. shouldn't let me?

Post a comment

Your comment will be anonymous unless you join the community. Or sign in with your social account: