In the previous part of this Object-Oriented Programming series, we discussed the basics of object-oriented programming concepts and their advantages and disadvantages. Similarly, we explored the concept of classes and objects, member functions, constructors and destructors. We also wrote some example codes in C++.
In this part of the series, we will delve deeper into object-oriented programming concepts.
Object as Function Argument and Return Type
Objects can also be passed as arguments to a function, which in turn can also return an object.
Array of Objects
An array of objects can be created in the same way as other variables. Private and protected members of a class can not be accessed through array members;
We can access the members of an array using the following syntax:
Pointer of objects and Member Access
Like creating pointers of other data types, we can also create pointers for classes. The pointer will hold the address of an object of class. The general form of the class's pointer declaration is
Members of the pointer can be accessed using the arrow operator (->)
Dynamic Memory Allocation for Objects and Objects Array
We can allocate dynamic memory for objects and object arrays like dynamic memory allocation for other data types.
class-name *pointer-name; //declaring a pointer
pointer-name = new class-name; //for a single object
pointer-name = new class-name[size]; //for an array of objects
For the de-allocation of memory
delete pointer-name; //De-allocating memory
Static data members and static function
Static Data Members
A Static data member is shared by or common to all the objects of that class. It is defined inside a class as a static.
Static Member Function
A member static function is a function which can only access static data members and can be invoked or called using the name or object of that class.
Constant Member Functions and Constant Objects
Constant member functions are those functions which can only use the data member of a class but cannot modify it. The constant member function is declared using the const keyword.
Both class member functions declaration and definition have const keyword on them. Once the function is declared as const, it cannot modify data members. If they try to alter data compiler will generate an error.
Constant member function can only invoke other constant member function of class. Display cannot call input function in the above case.
Like constant member data and function, constant objects cannot be modified. Constant objects can only have constant functions as they are guaranteed not to modify the output.
In C++, the "this" pointer is a special pointer that refers to the current instance of a class within its member functions.
There might be situations where constant objects must only change the particular data members. In such cases, the data member is declared as mutable keywords.
Thank you for reading this article. Please leave a comment below if you liked it.