C++

C++ Generic Types

Posted on December 12, 2013. Filed under: C++ | Tags: |

generic type

generic function

In a nutshell, generics enable types (classes) to be parameters when defining classes and methods. Much like the more familiar formal parameters used in method declarations, type parameters provide a way for you to re-use the same code with different inputs. The difference is that the inputs to formal parameters are values, while the inputs to type parameters are types.
The c++ keyword for generic is “template”:
#include
using namespace std;
template
T add(S a, U b, V c) {
return a+b+c;
}
int main() {
int x=1, y=2, z=3, s;
s=add(x,y,z);
cout<<s<<endl;
double x=1.00, y=2.00, z=3.00;
int s;
s=add(x,y,z);
cout<<s<<endl;
}

Generic types çan also be passed into class with < >, for example:

Bucky <int> bo(256, 105);

#include <iostream>

using namespace std;

template <class T>

class Bucky{

T first, second;

public:

Bucky(T a, S b){

first =a;

second=b;

}

T bigger();

};

template <class T>  //define function outside of class

T Bucky<T>::bigger(){

return (first>second?first:second);

}

int main() {

Bucky <int> bo(256, 105); //pass type variable to class constructor

cout<<bo.bigger():

}

Now the class have generic implementation for generic types, however, we still want to do the opposite, we want to have a specific implementation for a specific class type, we can do that by declare template specializations with “template<>”

#include <iostream>

using namespace std;

template <class T>

class Spunky{

public:

Spunky(T x) {

bout << x << ” is not a character” << endl;

}

};

template<>   //declare template specialization

class Spunky<char>{

public:

Spunky(char x){

count << x<< ” is indeed a character” << endl;

}

};

int main() {

Spunky <int> obj1(7);

Spunky <char>obj3(‘q’);

}

Advertisements
Read Full Post | Make a Comment ( None so far )

Polymorphism and virtue keyword

Posted on December 11, 2013. Filed under: C++ | Tags: |

The dictionary definition of polymorphism refers to a principle in biology in which an organism or species can have many different forms or stages. To apply the polymorphism principle to OOP, the language need to provide some way to allow parent class to contain the blue print of the specie and leave the implementation to subclasses.
In Java, polymorphism is supported by abstract methods/abstract class and interface. While abstract class allow partially implemented methods, the interface contains only method declarations. The implementation flexibility is left to the subclass. Unique to java, a class can implement multiple interfaces.
In C++, polymorphism is supported by virtue function/virtue class. C++ have no interface, however, C++ virtue keyword together with pointer, can act as interface.
Here is how the keyword virtue works:
When a function is prefixed with keyword virtue, the function refer to the function implementation in the subclass (if defined) intend of default implementation in parent class.
Virtue keyword is unique to C++, through pointer of the virtue function, parent class can access the function defined later in its subclasses (which is somehow the java interface try to accomplish.)
pure virtue function: a virtue function without default implementation.
virtue class: a class contains pure virtue function. virtue class can not be instantiated. When a virtue class contains only pure virtue functions, it is somehow the equivalent of java interface.
#include
using namespace std;

class Enemy {
public:
//virtual void attack()=0; //pure virtue function
virtual void attack() {
cout<<“enemy attack!”<<endl;
}
void defend() {
cout<<“ememy defend.”<<endl;
}

};

class Ninjia: public Enemy {
public:
void attack() {
cout << “ninja attack!” <<endl;
}
void defend(){
cout<<“ninjia defend.”<<endl;
}
int main () {
Ninjia n;
Enemy *enemy = &n //polymorphism, we can use the parent class’s pointer to reference many types of subclasses’ address
enemy.attack(); //due to “virtue” keyword, result is “ninja attack”
enemy.defend(); //normal function, the result is “enemy defend.”
n.defend(); //normal function, the result is “ninjia defend.”
}

Read Full Post | Make a Comment ( 2 so far )

Inheritance

Posted on July 11, 2013. Filed under: C++ |

Same as Java concept, C++ allow inheritance, with slightly different syntax.
========================
//Mother.h
class Mother{
public:
int publicv;
protected:
int protectedv;
private:
int privatev;
};

==========================
//Daughter.h
//class Daughter inherit all the public and protected variables and methods from class Mother
class Daughter: public Mother { }

====================
#Daughter.cpp
#include
#include “Mother.h” //has to come before #include “Daughter.h”
#include “Daughter.h”
using namespace std;

void Daughter::doSomething(){
publicv = 1;
protectedv = 1;
//no access to privatev
}

Read Full Post | Make a Comment ( None so far )

Operator Overloading

Posted on June 22, 2013. Filed under: C++ |

In c++ you can overload operators such as +, -, *, / etc.
The syntax is: add keyword “operator” before an operator, then treat the whole string as a function.

For example, to overwrite + operator.

In Sally.h

#ifndef SALLY_H
#define SALLY_H

class Sally
{
public:
int num;
Sally();
Sally(int);
Sally operator+ (Sally); //overwrite operator+,
//have a Sally object as function parameter
//return a Sally object
};
#endif

=========
In Sally.cpp

#include
#include
using namespace std;

Sally::Sally()
{}

Sally::Sally(int a) {
num = a;
}

Sally Sally::operator+(Sally aso) {
Sally newSally;
newSally.num = num + aso.num;
return(newSally);
}

====================
In main.cpp

#include
#include “Sally.h”
using namespace std;

main()
{
Sally a(3);
Sally b(4);
Sally c;      //create a Sally object

c = a + b;   // create another Sally object, assign num = a.num + b.num,

//then return the Sally object, assign to c.
bout << c.num<<endl;  //value is 7
}

Read Full Post | Make a Comment ( None so far )

friend functions and classes

Posted on April 19, 2013. Filed under: C++ | Tags: |

In C++, a class can give its own friendship to another class or to a function defined outside itself. The friend class and friend function then have access to the private class members (variables and functions) of the class that gives friendship. Like (almost) everybody are trying to (or forced to) give friendship to the king, the king didn’t give friendship to everybody; similarly, the c++ friendship is not mutual (why they don’t pick a better keywords such as privilege, access, etc.) –when class Joe set class King as friend, class King then can access class Joe’s private functions and modify class Joe’s private variables, which doesn’t mean class Joe can do the same to the class King.

The c++ friend keyword syntax is:
# include <iostream>
using namespace std;

class StankFist {
public:
StankFist() {stinkyVar=0;}
private:
int stinkyVar;

friend void stinkysFriend(StankFist &sfo);
};

void stinkysFriend(StankFist &sfo) {
sfo.stinkyVar=99;
cout<< sfo.stinkyVar<<endl;
}

int main() {
StankFist bob;
stinkysFriend(bob);
}

Read Full Post | Make a Comment ( None so far )

Composition

Posted on April 18, 2013. Filed under: C++ | Tags: |

C++ composition is almost the same as other object orented languages such as Java — you can use the objects of other classes as the class member of a class. The only c++ feature is you have to use member initializer list in the constructor to initialize the objects class members, whenever you use a class object inside another class.

#include “People.h”
#include “Birthday.h”
#include
using namespace std;

People::People(string x, Birthday bo)
: name(x),
dateOfBirth(bo)
{
}

Read Full Post | Make a Comment ( None so far )

const keyword

Posted on April 18, 2013. Filed under: C++ |

const keyword can declare variables that can not change. If you have a const variable in your class, you have to use member initializers to initialize them in the class constructor.

class Sally

{

public:

Sally(int a, int b); //constructor takes 2 variables, one assign to regVar, another to constVar

private:

int regVar;   //regular variable

const int constVar;  //constant variable

}

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

#include “Sally.h”

#include <iostream>

using namespace std;

Sally::Sally(int a, int b)  //constructor takes two parameters

: regVar(a),           //: tell c++ I will start a member initializer list, use comma as separator

constVar(b)         //const variable have to be initialized with this weird member initializer syntax

{} //no code here because const variable can’t be initialized in normal way.

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

Sally so(3,87); //caller assigned 3 to regVar, 87 to constVar.

const keyword allows C++ to create both ordinary objects and constant objects from a class containing both regular functions and constant functions. The constant object can not be modified.

Whenever you create a const object, you tell the compiler the object can not be modified, you can only access the constant members defined inside the class.

The syntax for const object is as follows.
in class body:
void Sally::printShiz2() const {
cout << ‘whatever’ << endl;
}

in header prototype:
void printShiz2() const;

in caller:
const Sally constObj;
constObj.printShiz2();

Read Full Post | Make a Comment ( None so far )

Deconstructors

Posted on April 18, 2013. Filed under: C++ | Tags: |

When a c++ object get destroyed (at the finishing of a program), it automatically calls a deconstructor to do stuff like house keeping.
The syntax of creating a deconstructor is ~Whateverclassname();
The deconstructor have no return type, no parameters and can not be overloaded. (c++ constructor have no return type, can have parameters and can be overloaded)

Note:

Compare to C++, Java have no destructor. The reason is that all Java objects are heap allocated and garbage collected. Without explicit deallocation (i.e. C++’s delete operator) there is no sensible way to implement real destructors. There is an inherited method called finalize, but this is called entirely at the discretion of the garbage collector. So for classes that need to explicitly tidy up, the convention is to define a close method and use finalize only for sanity checking (i.e. if close has not been called do it now and log an error).

Read Full Post | Make a Comment ( None so far )

Pointers and Pass by Reference

Posted on April 18, 2013. Filed under: C++ | Tags: |

Same as C, C++ can access variable memory address with pointer.

& is reference operator, which get the memory address of a (whatever type) variable.

* is dereference operator, which get the value of a pointer variable.

int fish =5; //declare a int variable

int *fishpointer;//declare a pointer variable
fishpointer = &fish;//assign the memory address of int variable fish to pointer variable fishpointer. &fish get memory address of int variable fish.

*fishpointer=10;//put 10 as the value stored in the memory address, which pointer variable fishpointer points to.

We can pass a variable to a function by reference. The following example, we pass the memory address of a char variable fish to function passByReference, the function put value 10 to the memory address of the char variable fish. The memory address or reference of char variable fish is passed as a parameter to the function, by a pointer variable fishaddress.

char fish = ‘a’;

passByReference(&fish);

void passByReference(int *fishaddress) {

*fishaddress=10;

}

Read Full Post | Make a Comment ( None so far )

Unary Scope Resolution Operator

Posted on April 18, 2013. Filed under: C++ |

unary scope Resolution operator :: is used when you have two variables with the same name (same or different type), one is global and other is local. To reference global variables, you need to use ::Avariable.

 

Read Full Post | Make a Comment ( None so far )

« Previous Entries

Liked it here?
Why not try sites on the blogroll...