Off Topic > Off Topic
Programming Megathread
SubDaWoofer:
yet again i am trying to into code again and yet again i forget how classes work
note: using C++ this time
Pecon:
--- Quote from: SubDaWoofer on February 16, 2017, 05:02:58 PM ---yet again i am trying to into code again and yet again i forget how classes work
note: using C++ this time
--- End quote ---
Classes are the 'formal' way of making objects in C++ (the 'informal' way is via a struct). They provide slightly more functionality than structs and are written a little more verbosely. Basically you define the class and specify all the values and methods of that object.
--- Code: ---class thingHandler
{
public int things;
private bool thingsAreHandled = false;
public void handleThings(); // member function
}
// Constructor method
thingHandler::thingHandler(int start)
{
things = start;
}
void thingHandler::handleThings()
{
thingsAreHandled = true;
}
int main()
{
thingHandler TH = new thingHandler(20);
TH.handleThings();
TH.things += 10;
}
--- End code ---
Thanks for the corrections, Headcrab.
Headcrab Zombie:
--- Quote from: Pecon on February 16, 2017, 08:50:30 PM ---It's been a while since I wrote any C++ so I'm not 100% sure if the 'new' declaration is right.
--- End quote ---
It would be thingHandler TH = new thingHandler(20);
Also you want the constructor declaration either inside the class, or prepended with thingHandler::. And it doesn't have any return type (not even void):
thingHandler::thingHandler(int start)
{
things = start;
}
SUSHI:
--- Quote from: Pecon on February 16, 2017, 08:50:30 PM ---They provide slightly more functionality than structs
--- End quote ---
Not really. The only difference between a structure and a class is that by default, a structures members are public and it also publicly inherits it's base class.
When creating a class using new, it will not be deleted when it goes out of scope. You must delete it some point when you're finished with it, or you will leak memory.
--- Code: ---thingHandler TH = new thingHandler(20);
TH.handleThings();
TH.things += 10;
delete TH;
--- End code ---
You can also create your class with automatic storage duration, which will handle cleanup automatically when it goes out of scope.
--- Code: ---thingHandler TH(20);
TH.handleThings();
TH.things += 10;
--- End code ---
Metario:
--- Quote from: SUSHI on February 16, 2017, 11:14:06 PM ---When creating a class using new, it will not be deleted when it goes out of scope. You must delete it some point when you're finished with it, or you will leak memory.
--- End quote ---
oops