Prerequisites:
- Should possess experience basic programming concepts.
- Should know the concepts(Object, Class, Attributes, Method) in OOP theoretically.
- Syntax
- Access specifier
- Constructor and Destructor
- Methods
- Quick Code Explanation
- Syntax:
- Access Specifiers:
- Constructor:
Now, what does a Constructor DO? A constructor is a function that gets called automatically when you declare an Object. That means when the compiler executes line no. 33 it immediately executes constructor. In our case, it will initialize a,b member variables with p and q and will finally print "Automatically Executed!".
Again a question! Can we only have one constructor in a class? The answer is NO! You can have as many Constructor you want. depending on your number of arguments and data types of arguments compiler will call the appropriate constructor.
- Destructor:
- Method:
In lines 35 and 36, you can see how the method is called on object "Obj" using the dot ' . ' operator. Notice the parentheses"( ) " written in a call. Always Remember that method will always have parentheses. when we access an attribute value(line no. 34, str1 is the attribute), we don't write parentheses but in the case of method, we need to write them, That's the difference between accessing attribute value and method call.4
- Quick Code Explanation:
- In the following Code, "Mynumbers" is the name of the class, which has 'x' and 'y' private integers 'a' and 'b' public integers, str1 private string, and str2 public string. which all are the attributes of the object.
- It has a constructor that takes two integer arguments and assigns them to private variables x and y and prints Automatically executed
- It has two methods, "product" and "greater" and a destructor that prints "Everything ended!"
- when execution starts at line 31, the object of type Mynumbers gets declared with two integer arguments, which calls the constructor which initializes values and prints the content
- At line 34 str1 public attribute value is accessed and printed.(Notice NO parentheses)
- next two lines call methods on object Obj which give respective outputs.
- At line no. 37, A public method that has access to all the private attributes, is called on object Obj hence, ultimately private members are called in the main function with help of the intermediate public method.
You can see the output Below!
So this covers like most Basic things that are needed in object orientation in C++, I hope this post was informative to you and you learned something from it. let me know what you think about OOP in the comments down below, Share doubts, thoughts, suggestions, anything you want there.
We'll catch-up in the next post!
Thank you for reading!😄
Peace✌
2 comments:
Very nice efforts
You are working hard dude. Accurate and perfect explanation..🙌🙌
Post a Comment