OOP in C++

Disarikan dari sini¬†–> slightly rephrasing from this wonderful site (for personal purpose)
–> now that I’m half of reading it, that is just such an awesome site. Thanks NTU ūüôā

  1. Why OOP?
    – to avoid re-invent the wheels
    – to make parts/components reusable
    1.1. Traditional Procedural-oriented languages
    – not reusable, because function is likely to reference the headers, global variables and other funcs.
    – not suitable of high-level abstraction
    – separate the data structures and algorithms of the software entities>> hardware faults can be isolated, but software faults could affect other programs running in computers1.2 OOP languages
    – basic unit is a class:
    >> encapsulates both the static attributes and dynamic behavior within a box
    >> specifies the public interface for using these boxes
    – well encapsulated, that it is easier to reuse the classes
    – OOP combines the data structures (in data members) and algorithms (member functions) of a software entity inside the same box
  2. OOP Basics
    2.1. Classes & Instances
    – Class: DEFINITION of objects of the same kind
    >> a blueprint/template/prototype
    >> defines & describes the static attributes and dynamic behaviors common to all objects of the same kind
    – Instance: REALIZATION of a particular item of a class
    >> an instantiation of a class
    >> all the instances of a class have similar properties (as described in the class definition)
    – object: usually instance, but can also be a class (used loosely)2.2. Class: 3-Compartment Box encapsulating Data & Functions
    -a class:
    >> classname (identifier)
    >> class members (data members + member functions)- a class can be visualized as:
    >> classname (identifier)
    >> data members/variables (attributes, states, fields) –> static attributes of the class
    >> member functions (methods, behaviors, operations) –> dynamic operations of the class

    – value of data member: class state
    – member function: class behavior

    – in UML (notation):
    >> instanceName:Classname
    >> public members, denoted with +
    >> private members, denoted with –

    naming convention:
    – class: noun or noun phrase, and initial-capitalized, meaningful & self-descriptive
    >> e.g., SoccerPlayer, FileInputStream,
    Рdata members (variables) noun or noun phrase, first word is lowercase, the rest are initial-capitalized
    >> e.g., fontSize, roomNumber,first word is lowercase, the rest are initial-capitalized, + parentheses
    Рmember functions: verb or verb phrase,
    >> e.g., printLine(), getArea()

    2.3. Creating Instances of a Class
    You need to:
    – Declare an instance identifier/name of a particular class
    – invoke a constructor to construct the instance
    >> allocate storage for the instance and initialize the variables

    example
    Construct 3 instances of Circle, named (of the instances) c1, c2, c3, with 3 ways (either specify radius or/and color, or using the default value)

    Circle c1(1.2, "red");
    Circle c2(3.4); //using default color
    Circle c3; //using default radius and color
    Alternative: invoke the constructor explicitly
    Circle c1 = Circle(1.2, "red");
    Circle c2= Circle(3.4);
    Circle c3 =Circle();

    2.4. Dot operator to reference a member of a object
    To reference data or member function of a object, you  must:
    – using dot operator instanceName.memberName

    E.g., to invoke the getArea() function of instance c1:
    – c1.getArea()

    2.5. An OOP example
    Class diagram (class definition vs instances)
    belajar

    code

    class Circle{
    private:
    double radius;
    string color;
    
    public:
    Circle(double r=1.0, string c="red"){
    radius =r ;
    color =c;
    } //constructor with default values
    
    double getRadius(){
    return radius;
    }
    
    ...
    }

    when referring (after instantiation) in the main function
    (don’t forget to include iostream¬†(for IO function), string (for using string), and using namespace std; )

    cout<<"Radius"=<<c3.getRadius()<<endl;

    (and to compile using “g++ -o OutputFileName.exe SourceCode.cpp”)

    2.6. Constructor
    – to initialize all the data members
    – has no return statements
    – are not inherited

    2.7 Default Arguments for functions
    – put it in the function header
    – e.g.
    int sum(int n1, int n2, int n3=0, int n4=0, int n5=0);

    int main(){
    cout<<sum(1,1)<<endl;
    }

    int sum(int n1, int n2, int n3, int n4, int n5){
    return n1+n2+n3+n4+n5;
    }

    2.8. Information hiding an encapsulation
    – principle of information hiding
    >> object communicate w/ each other using well-defined interfaces (public functions)
    >> implementation details are hidden/encapsulated within the class
    >> this information hiding facilitates reuse of the class
    >> data member of a class are typically hidden from outside world (access control modifier: private)
    >> access to private data members are provided via public functions, getters (to read) and/or setters (to modify)

    2.9

Inheritance (C++)

Reference dari sini dan sini

Inheritance:
– allows you to create a hierarchy of classes
— generalized classes (e.g., class Animal)
— various classes of more specific nature (e.g., class Dog & class Cat) inheriting the general aspects of more generalized classes
base class vs derived class
derived classes:
>> inherent the traits that are general to parent class base class
>> but derived classes will have specific attributes

One possibility:
– starting a program with abstract idea
– then implemented by specific classes

Base class: (general class)
Рcontain functions that all the derived classes will need
Derived classes: (more specific class)
– inherit functions and variables from base class
a class can be both a base class or a derived class

encapsulation: the hidden nature of classes (e.g., protected & private)

Restriction keyword (level of data hiding):
1. Public (variable & function) –> the most open
– inheritable by derived class
– accessible to outside functions & code, when they are elements of a specific instance of a class
– usually to give and take information to the outside world (interface)
– a well-designed will have no public fields, everything should go through the class’s functions
– getters: functions that retrieve variables
– setters: functions that change values

2. Protected
– variables: not accessible by functions and code outside the class
Рbut are accessible to their derived classes
inherited but hidden from outside
– access control for important aspects to a class that must be passed on without allowing it to be accessed

3. Private -> highest level of data-hiding
– not accessible by functions and code outside the class
Рnot accessible to their derived classes
– if you do not wish derived classes to access a method, declare as private

Derived class, example

class Cat : public Animal
{
public:
int fur_color;
void purr();
void fish();
void markTerritory();
}

– derived class has access to the data members (variables and functions) of a base class
– specific instance of the derived class possessing data
– two different Bear objects:
>> having the same member variables and functions
>> having DIFFERENT information stored in their variables
Рif a class Animal with an object, BigAnimal
– two different Bear objects will not have access to the data within BigAnimal
– only posses variables and functions with the same name and of the same type

Next:
Class design in C++

– subclasses –> derived class

– a function should be virtual when the implementation is likely to differ from subclass to subclass

Related term:
– polymorphism

Kelas (C++)

disarikan dari sini dan sini
not yet, class design

Ide dasar kelas:
encapsulation: to make programs more modular
– the outside world doesn’t need to know exactly what data is stored inside the class
Рthe outside world just need to know which functions it can use to access the data
– advantage: allow the implementation to change more easily
>> because nobody have to rely on it (the detail of a class), except the class itself

>> Kelas: koleksi data, related to a single object type [house]
– include information regading real world object –> variables [items inside house]
– include functions [door] to access the data
– posses the ability to inherit from other classes

Make sure to know the difference(s) between:
– instance
– class member
– instance variable vs class variable
– instance method vs class method

Member of a class:
– data / member variable / (instance variable) / class attribute / property / field
– function / method

Other term (please check later):
– instance variable -> similar to class variable (but not the same)
– instantiated object
– instance = object?
– object instance
– invoke an object = instantiate an object/create an instance?
– copies of instance variables

need to consider sentence:
– all instances of an object have their own copies of instance variables
– one object instance can change values of its instance variables without affecting all other instances
–¬†instance variables can be used by all methods of a class unless the method is declared as static
–¬†a class of objects that describes a set of objects

Syntax
– keyword class
– nama kelas
– open bracket {
>> degree of restrictions: either public, procted, private
— public
— protected: functions outside the class to access the variable
— private (similar to protected, but will be different, related to inheritance)
– restriction keyword, colon :
– variables
– functions (usually prototype –> why?), ended with semicolon ;
>> two basic and need functions (neither return arguments/return value):
— Constructor, className
—– to initialize variables
—– if you don’t need to perform any initialization, the compiler will create a¬†default constructor
— Destructor, ~className
—– to clean up after the class, including freeing any memory allocated
—– if you don’t need to do anything special in the destructor, the compiler will create a¬†default destructor

Why separate /having degree of restrictions?
>> it makes the class easier to use
– the key idea is to separate
— the interface you use
— the way the interface is supported
— the way the interface is implemented

How it works
1. Programmer declares an instance of the class
2. Constructor will be automatically called
3. Destructor is called when the class is no longer usable
>> when the instance of the class is no longer needed, e.g.:
– program ends
– class reaches the end of scope
– memory is deallocated using delete

contoh, diambil dari cprogramming.com (diketik ulang)

#include<iostream>
using namespace std;
class Computer
{
public:
Computer();
~Computer();
void setspeed(int p);
int readspeed();

protected:
int processorspeed;
};

then

Computer::Computer() //constructor --> can accept arguments
{
processorspeed = 0
}

Computer::~Computer()
{
}
void Computer::setspeed(int p)
{
processorspeed=p;
}

int Computer::readspeed()
{
return processorspeed;
}

finally

int main()
{
Computer compute; // create an instance
compute.setspeed(100);
// means that it assign computer.processorspeed (protected)
cout<<compute.readspeed();
// calling a public func readspeed who return value from (protected) var processorspeed
}

CLASS DESIGN

  1. Decide the public interface for the class

Mengokohkan yang goyah (C++)

Beberapa konsep dasar C++ yang rasanya belum mantap:
konsep OOP in C++ –> menarik, dari spore
class design in c++
designing a program
– pointer
inheritance
STL (standard template library)
const (why do we even need?)
static
debugger and debugging techniques
linked list, recursion, binary trees
– custom data type (enumerated types, structs)

C:
c preprocessor:
>> directive
>> constants
>> macros

Advance:
list of interesting books

Mixed up:
OOP terminology @ Python
class & instance attribute @ Python
classes (formal reference) @ Python

Table in blog

Code:

<table border="2" cellspacing="3" cellpadding="5">
<tbody>
<tr>
<td><strong>Header1</strong></td>
<td><strong>Header2</strong></td>
<td><strong>Header3</strong></td>
</tr>
<tr>
<td>Content1</td>
<td>Content2</td>
<td>Content</td>
</tr>

Example:

Header1 Header2 Header3
Content1 Content2 Content

Import dalam python

Conclusion:
1. From fileName import className
2. after importing, instantiate class
variable = className()
var1 = variable.defName1InsideClass(param1)
variable.z = defName2InsildeClass(param2)

3. From fileName import layer1defName
4. after importing, can directly call
defName()

====================

InitialFile.py #ig

Code .. Comment 
class WBName(WB):  val0, val1, val2, val3 = range(4) sejenis constant
(class attribute)
def __init__(self):

import MainLib
from MainLib import defML1
#import dll if necessary
–> will be explained later

self.var1InitFile=False
self.var2InitFile \
=MainLib.KelasML1() 
#tsfra
#[1]

self.var3InitFile=self.val2
#[2]

basically: constructor/setting up

#[1]:
instantiate self.var2InitFile1 using MainLib.KelasML()

–> basically, inisialisasi basic attributes/variables

#[2]:
assign var w/ previously defined constant

def Activated(self):

from MainLib import defML2
from stdFunc1 import standardFunction1

self.IFSS_mainwindow. \
func1set(standardFunction1, self.IFSS_formmain)

self.IFSS_formmain. \
func2()
self.var4InitFile=defML2()

 #when module is activated
def Dectivated(self):

from MainLib import defML3

self.IFSS_mainwindow. \
func3remove(self.IFSS_formmain)
defML3(self.var4InitFile)

 #when module is activated

.

.

def Initialize(self):
self.InitFile_ShowSomething()
 #when sw is loaded
def InitFile_ShowSomething(self):
import otherFile_MainForm
from stdFunc import standardFunction

try:

self.IFSS_mainwindow=stdlib.stdfuncc()
self.IFSS_formmain = standardFunction.functionSomething()
self.IFSS_formmain.attribute1 = otherFile_MainForm.KelasForm()

except Exception, e:
doSomething()# other form functionalities

===================

MainLib.py #sfr

Code .. Comment
from otherFileName import ClassName1, ClassName2

from AdditionalLib import KelasAL1

..
def defML1(self):
pass
def defML2():
locvar =ClassName1()
return locvar
def defML3(obs):
stdfunction(obs)
def defML4(ptstart, ptend):
locresult = ptstart.def2KelasAL1(ptend)
def KelasML1: def __init__(self):

#static
self.var1KelasML1={}
self.var2KelasML1=[]

#dynamic
self.var3KelasML1=None
self.var4KelasML1=False

self.var5KelasML1=KelasAL1(X=0.0, Y=0.0, Z=0.0)

if KelasML1 is instantiated, some basic attributes will be created/assigned

will call

====================

AdditionalLib.py #cls

Code .. Comment
class KelasAL1:

#d3

def __init__(self, Vector=None):
self.var1KelasAL1=0.0
self.var2KelasAL1=0.0
self.var3KelasAL1=0.0if Vector:
self.var1KelasAL1=Vector.x
self.var2KelasAL1=Vector.y
self.var3KelasAL1=Vector.z
attribute dasar, akan sering dipakai
def def1KelasAL1(self):
pass
def def2KelasAL1(self, destinationPoint):
return destinationPoint.X-self.X

Additional information

Basic function (or attributes):

Initialize() = when program is loaded, even before the module is activated
Activated() = when module is activated (WB)
Deactivated() = when user switch to another module(WB), or leave program