Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a simple class in C++?

I have been reading a lot of tutorials on C++ class but they miss something that other tutorials include.

Can someone please show me how to write and use a very simple C++ class that uses visibility, methods and a simple constructor and destructor?

like image 729
Babiker Avatar asked May 14 '09 21:05

Babiker


People also ask

Can we write class in C?

C Classes A class consists of an instance type and a class object: An instance type is a struct containing variable members called instance variables and function members called instance methods. A variable of the instance type is called an instance.

What is a class in C programming?

Class is an abstract data type similar to the C structure. A class is a representation of objects and some set of operations that can apply to such objects. The class consists of Data members and methods. The primary purpose of a class is to hold data/information.

What is class with syntax and example?

In object-oriented programming, a class is an extensible program-code-template for creating objects, providing initial values for state (member variables) and implementations of behavior (member functions or methods).


2 Answers

Well documented example taken and explained better from Constructors and Destructors in C++:

#include <iostream>            // for cout and cin  class Cat                      // begin declaration of the class {   public:                      // begin public section     Cat(int initialAge);       // constructor     Cat(const Cat& copy_from); //copy constructor     Cat& operator=(const Cat& copy_from); //copy assignment     ~Cat();                    // destructor      int GetAge() const;        // accessor function     void SetAge(int age);      // accessor function     void Meow();  private:                      // begin private section     int itsAge;                // member variable     char * string; };  // constructor of Cat, Cat::Cat(int initialAge) {   itsAge = initialAge;   string = new char[10](); }  //copy constructor for making a new copy of a Cat Cat::Cat(const Cat& copy_from) {    itsAge = copy_from.itsAge;    string = new char[10]();    std::copy(copy_from.string+0, copy_from.string+10, string); }  //copy assignment for assigning a value from one Cat to another Cat& Cat::operator=(const Cat& copy_from) {    itsAge = copy_from.itsAge;    std::copy(copy_from.string+0, copy_from.string+10, string); }  // destructor, just an example Cat::~Cat() {     delete[] string; }  // GetAge, Public accessor function // returns value of itsAge member int Cat::GetAge() const {    return itsAge; }  // Definition of SetAge, public // accessor function  void Cat::SetAge(int age) {    // set member variable its age to    // value passed in by parameter age    itsAge = age; }  // definition of Meow method // returns: void // parameters: None // action: Prints "meow" to screen void Cat::Meow() {    cout << "Meow.\n"; }  // create a cat, set its age, have it // meow, tell us its age, then meow again. int main() {   int Age;   cout<<"How old is Frisky? ";   cin>>Age;   Cat Frisky(Age);   Frisky.Meow();   cout << "Frisky is a cat who is " ;   cout << Frisky.GetAge() << " years old.\n";   Frisky.Meow();   Age++;   Frisky.SetAge(Age);   cout << "Now Frisky is " ;   cout << Frisky.GetAge() << " years old.\n";   return 0; } 
like image 116
TStamper Avatar answered Oct 20 '22 05:10

TStamper


Even if he is a student, worth trying to answer because it is a complex one not that easy at least for a new Visitor of C++ :)

Classes in C++ serve an intersection of two design paradigms,

1) ADT :: which means basically a new type, something like integers 'int' or real numbers 'double' or even a new concept like 'date'. in this case the simple class should look like this,

class NewDataType { public: // public area. visible to the 'user' of the new data type. . . . private: // no one can see anything in this area except you. . . . }; 

this is the most basic skeleton of an ADT... of course it can be simpler by ignoring the public area! and erasing the access modifiers (public, private) and the whole thing will be private. but that is just nonsense. Because the NewDataType becomes useless! imagine an 'int' that you can just declare but you CAN NOT do anything with it.

Then, you need some useful tools that are basically not required to the existence of the NewDataType, but you use them to let your type look like any 'primitive' type in the language.

the first one is the Constructor. The constructor is needed in many places in the language. look at int and lets try to imitate its behavior.

int x; // default constructor.  int y = 5; // copy constructor from a 'literal' or a 'constant value' in simple wrods. int z = y; // copy constructor. from anther variable, with or without the sametype. int n(z); // ALMOST EXACTLY THE SAME AS THE ABOVE ONE, it isredundant for 'primitive' types, but really needed for the NewDataType. 

every line of the above lines is a declaration, the variable gets constructed there.

and in the end imagine the above int variables in a function, that function is called 'fun',

int fun() {     int y = 5;     int z = y;     int m(z);      return (m + z + y)     // the magical line. } 

you see the magical line, here you can tell the compiler any thing you want! after you do every thing and your NewDataType is no more useful for the local scope like in the function, you KILL IT. a classical example would be releasing the memory reserved by 'new'!

so our very simple NewDataType becomes,

class NewDataType { public: // public area. visible to the 'user' of the new data type.     NewDataType()     {          myValue = new int;         *myValue = 0;     }      NewDataType(int newValue)     {         myValue = new int;         *myValue = newValue;     }      NewDataType(const NewDataType& newValue){          myValue = new int;         *myValue = newValue.(*myValue);     } private: // no one can see anything in this area except you.     int* myValue; }; 

Now this is the very basic skeleton, to start building a useful class you have to provide public functions.

there are A LOT of tiny tools to consider in building a class in C++,

. . . .

2) Object :: which means basically a new type, but the difference is that it belongs to brothers, sisters, ancestors and descendants. look at 'double' and 'int' in C++, the 'int' is a sun of 'double' because every 'int' is a 'double' at least in concept :)

like image 22
Khaled Alshaya Avatar answered Oct 20 '22 04:10

Khaled Alshaya