You are on page 1of 17

University of Minnesota

Twin Cities Campus

System-Level Modeling and Verification for Communications C++ review Prof. Xiaofang Zhou ASIC & Systems, Dept. of Microeletronics FUDAN University Shanghai, CHINA

Outline
What's new or improved in C++ Class
constructor & destructor copy, type cast, arry, this inheritance, access label & protected, virtual class data, friend, type cast, overload operators

Templates
function template class template

Homeworks
2

What's new or improved in C++


Comments, both /* */ and line comments // <iostream.h> instead of <stdio.h>
send to STDOUT cout << "Hello world!" << j << x + 1 << endl; get from STDIN cin >> a >> b; // get two input and store in a and b

Type cast, both (type) expr and type(expr) auto, static inside function scope extern, static in globel scope
extern int b = 5; int b; extern int b; // definition // definition // reference
3

What's new or improved in C++


new/delete, replace malloc/free p = new type; delete p; // scalar p = new type [size]; delete [] p; // array reference, a very safe replacement for pointer int & a; // wrong int & a = b; // ref must be initialized function with ref arguments function return ref, don't return a ref to auto variable. Can be used as lvalue expression
int & index(int i) { return a[i];} // define index(9) = 5; // call
4

Review Pointer
a scalar: int a; P to scalar: int * pa; func def: func: int *pf(int, int); int a (int, int); func P: int (*pf)(int, int); func P: int *(*pf)(int, int);
pf is a pointer to function, the function takes two int type arguments, returns a pointer to int

What about this one: int *(*p[2])(int, int);


array of two element, each element is a pointer to function. The function takes two int type arguments, and returns a pointer to int.
5

What's new or improved in C++


inline function, replacement of MACRO
inline int isnumber(char c) { return (c >= '0' && c <= '9') ? 1 : 0; } if (isnumber(c)) { } else { }

inline function will be compiled into your code, not linked with your code later.
define the body of inline function before calling.
6

What's new or improved in C++


Default arguments
Arguments can has their default values.

Variable arguments
#include <stdarg.h> int max(int n, int num) { va_list ap; va_start(ap, num); study the stdarg.h, and learn how to use va_list, va_start, va_arg, va_end, etc It's safer to use function with default argument. int max(int=-1, int=-1, int=-1, int=-1);
7

What's new or improved in C++


Function overload int abs(int val) {} long abs(long val) {} float abs(float val) {} main () {
int a = -10; long l = 0xfffff; float f = -0.1234; count << abs(a) << newl << abs(l) << newl << abs(f) << newl;

} avoid ambiguous definitions void fun(int a, int b=4); // so far so good void fun(int i); // wrong.
8

Structure
structure in C++ is similar to class, but all data and methods are public by default. typedef myStruct { int * buffer; int len; } myStruct s; myStruct *ps; ps->len // i.e. (*ps).len *ps->buffer // i.e. *(ps->buffer) ++ps->buffer // i.e. ++(ps->buffer) (++ps)->buffer // ++ps, then ps->buffer *++ps->buffer //++(ps->buffer), get point ++*ps->buffer //inc the variable ps->buffer points to &ps->len // i.e. address of ps->len
9

Class
Class and object, pointer to object object data, object method, class data
data can't contains initial value data can't be modified by auto/extern/register method with body defined in class is inline. method arguments can contians default values Protect the object data, set / get method.

private vs. public

10

Sample Class, Constructor, etc

Class with two private data, and set/get methods

class Point { private: int x, y; public: Point(int iX=0, int iY=0); // X::X(??? ) virtual ~Point(); // virtual X::~X() int X() {return x;} int X(int iX) {int oX=x; x=iX; return oX;} int Y() {return y;} // define inline method int Y(int); }; Point::Point(int iX, int iY) { x = iX; y = iY; } //Point:: select a correct scope Point::~Point() { ;/*Do nothing*/ } // never call exit() in destructors inline Point::Y(int y) { int oY=this->y; this->y=y; return oY; } Point *p; void main() { p = new Point(1,2); cout << p->X() << ',' << p->Y(); }

, since y > p p->x, s s bers e c m c e a m t ' Ca n rivate p e r ' y th e

Constructor shall have no return type, not even void. inline method can be defined inside or outside class body. Method can be overloaded. Arguments may take default values. Inside the body of a method, you can refer to the this pointer. "this" is a hidden pointer points to the object calling the method. 11

Copy Constructor
Construct a new object by existing ones. class Point { Point(const Point &); // X::X(const X&) };

Point::Point(const Point &P) { x = P.x; y = P.y; } Point *p, *q; void main() { p = new Point(1,2); q = new Point(*p); cout << q->X() << ',' << q->Y() << endl; }
12

Copy method

copy method is called when doing P1 = P2. i.e. overload the default '=' operator Very similar to constructors, but shall return a value, and check for self copy copy method shall return a constant reference of the object being assigned

class Point { const Point& operator=(const Point& P); // const X& X::operator=(const X&) }; const Point& Point::operator=(const Point& P) { if (&P != this) { x = P.x; y = P.y; } // must avoid self-assignments return *this; } Point *p, Q, R, S; void main() { p = new Point(1,2); Q = *p; cout << Q.X() << ',' << Q.Y() << endl; Q = Q; cout << Q.X() << ',' << Q.Y() << endl; S = R = Q; // return type is const & so that this line won't be parsed as (S = R) = Q cout << S.X() << ',' << S.Y() << endl; } Don't rely on any C++ default copy method. Remember the example of deep-copy in SysVlog?

13

Array of objects
Initialize array of objects with initialize-list
Point a[] = {Point(), Point(1, 2), Point(3, 4)}; void main() { cout << a[0].X() << ',' << a[0].Y() << endl; cout << a[1].X() << ',' << a[1].Y() << endl; cout << a[2].X() << ',' << a[2].Y() << endl; }

Since the data of Point is private, you can't initialize a Point object in this way:
Point b = {5, 6}; // Wrong

14

Constructor as type cast function


Constructor will be called automatically void main() { Point a(5); // Normal case cout << a.X() << ',' << a.Y() << endl; a = 6; // 6 is type-casted to Point cout << a.X() << ',' << a.Y() << endl; a = Point(7);// type case, same as (Point)7 cout << a.X() << ',' << a.Y() << endl; } X::X(T1, T2, ), change the type of (T1, T2..) to X

15

Have objects as object member?


Object members constructed in declare order, and destructed in the reverse order. class Line { private: Point s, e; // here we have some object inside another object public: Line(int sX=0, int sY=0, int eX=0, int eY=0); Line(const Point &S, const Point &E); virtual ~Line(); const Point & Start(); const Point & Start(const Point &); // const Point & End(); // const Point & End(const Point &); }; Line::Line(int sX, int sY, int eX, int eY) : s(sX, sY), e(eX, eY) {} Line::Line(const Point &S, const Point &E) : s(S), e(E) {} Line::~Line() {}

f list is o r e d The or portant n o t im

const Point & Line::Start() { return s; const Point & Line::Start(const Point & Point *pS = new Point(s); s = S; return *pS; }

} S) { // can't say Point oS(s); ; return oS; // can't return a ref to local variables

void main() { Line L(6,7,8,9); Point S = L.Start(); cout << S.X() << ',' << S.Y() << endl; } Also valid for non-class type data: Point::Point(int iX, int iY) : x(iX), y(iY) {}

16

Inheritance and access label


Make extension to a class by inheritance class Derived : acc_label Base { // put something new here } // acc_label is either public or private All private member of Base are still private in Derived. If access label is private, all public member of Base also becomes private in Derived. If access label is public
all public member of Base are still public. all "protected" member of Base are accessible by Base members and friends, and by Derived members. But not Derived friends and ordinary users.

The default label is private for derived class, and is public for derived structure
17

Constructor of Derived
Constructor of Base will be called first, then constructors of member objects class Derived : public Base { classX member1; classY member2; Derived(arg_list); } // acc_label is either public or private

Derived::Derived(arg_list) :Base(arg), member1(arg1), member2(arg2), { // body of constructor } For multiple inheritance, put all base constructors in the list class Derived : public Base1, private Base2 { Derived(arg_list); } // acc_label is either public or private Derived::Derived(arg_list) :Base1(arg), Base2(arg) { /* body */ }
18

'protected' and abstract class


A 'protected' member can't be access from

outside When all constructors are labeled protected, no object can be instanciated from the class. It's called abstract class You still can make derived class from am abstract class, since protected member can be access from methods in derived class.

19

Method hidden
class int }; class int }; Base { func(int, int); Derived : public Base { funt(int); // hides func in the Base

Base B; Derived D; B.func(0, 0); // calls Base::func D.func(0); // calls Derived::func D.func(0, 0); // error: func with two arguments is hidden D.Base::func(0, 0); // ok: calls Base::func

20

Overload, Link at compile time

Overload function are linked at compile time. Type of object pointer are resolved at compile time. #include <iostream.h> ///////////////////////////// // Box class Point { Box::Box(int S, int X, int Y) int Area(); :Point(X, Y), size(S) {} }; Box::Box(int S, const Point &P) : Point(P), size(S) {} class Box : public Point { private: int Box::Area() {return size * size;} int size; Box::~Box() { } public: Box(int S=0, int X=0, int Y=0); ///////////////////////////// Box(int S, const Point &P); // main int Area(); virtual ~Box(); void main() { }; Point * p; Box * b; 36 ///////////////////////////// Box B(6, 1, 2); // Point 0 b = &B; p = b; int Point::Area() { cout << b->Area() << endl return 0; << p->Area() << endl; } } 21

Virtual function, Link at run-time


Virtual function, type of object pointer are resolved at run-time. #include <iostream.h> ///////////////////////////// // Box class Point { Box::Box(int S, int X, int Y) virtual int Area(); :Point(X, Y), size(S) {} }; Box::Box(int S, const Point &P) : Point(P), size(S) {} class Box : public Point { private: l int Box::Area() {return size * size;} virtua int size; s y a Box::~Box() { } alw public: Box(int S=0, int X=0, int Y=0); ///////////////////////////// Box(int S, const Point &P); // main int Area(); virtual ~Box(); void main() { }; Point * p; Box * b; 36 ///////////////////////////// Box B(6, 1, 2); // Point 36 b = &B; int Point::Area() { p = b; return 0; cout << b->Area() << endl } << p->Area() << endl; } 22

Pure Virtual Function


Virtual function without a body (who's body is defined as '=0') is a pure virtual function.

class Base{ virtual int Area() = 0; }


Never call pure virtual function directly. A class containing (or inheriting) one or more pure virtual functions is an abstract base class. Derived class shall implement the pure virtual function.

23

Class data
'static' data in class is a class level data Class data are shared between all its objects Class data shall be defined somewhere in your code
class X { private: static int CD; } static int X::CD=5; ..in your method.. X::CD++; this->CD;

// this is only a reference // define with initial value // access class data // class data has no this pointer
24

friend function

Class can declare some functions to be friend.


Friend Friend Friend Friend functions can access private elements of the class functions can also be a inline function function has no this-> pointer is actually a normal function authorized to access private members

Class can declare some method of other class as friend. Or other class as friend.

class B; class C; class A {public: int func(B&);} class B { friend int A::func(B&); friend class C; }

25

type cast
type cast a class to another type ( along

with modifiers like * [] () const volatile etc)


class X { operator type ();} class X { virtual operator type ();}

26

overload the operators

Redefine C++ operators


For all existing operators, except . .* :: ?: Can be virtual, except new delete = Can't defined your own operators Can't redefine precedence or associativity Hint: binary operators as friend function, unary operators as class operator method

class Point { Point operator - (); friend Point operator+ (const Point &, const Point &); }; Point Point::operator - () { return Point(-x, -y); } Point operator+ (const Point &a, const Point &b) { int x, y; x = a.x + b.x; y = a.y + b.y; return Point(x, y); } void main() { Point A(1, 2), B(5, 8), C; C = - A + B; cout << C.X() << ", " << C.Y() << endl; } 27

Function Template
Generic Programming
writing code that's independent of any particular type
#include <iostream.h> template <typename T> T abs(const T &var) { return (var >= 0) ? var : -var; }
Can name. y m um f er T is a d ou pr e y g n i th be any

template <typename T> inline T sqr(const T &var) { return var * var; } void main() { int a; float b; a = -5; b = -123.456; cout << abs(a) << ", " << abs(b) << endl; cout << sqr(a) << ", " << sqr(b) << endl; cout << abs<signed char>(-60) << ", " << abs<long>(-60) << endl; } sqr() can work on any class type when * is overloaded.

rload? e v o g sin Still u bs(int); ; int a bs(float) a float plate try tem

3.456 5, 12 41.4 52 25, 1 <, 60

n m e ca i t e m e f or iler so Comp a proper typ set e an deduc e. Or user c e> at templ ly via <typ al m an u 28

Nontype template parameter


nontype parameter in template
#include <iostream.h> template <size_t N, typename T> T max(T var[N]) { T ans; int i; ans = var[0]; for (i = 1; i < N; i++) { if (ans < var[i]) {ans = var[i];} } return ans; } int a[] = {1,2,3,4,-1,-2,-3}; void main() { cout << max<7, int> (a) << endl; }
29

Class with template

When using a class template, we must specify a valid type for the template parameter.
template <class T> void Vec<T>::dump() { int i; cout << a[0]; for (i = 1; i < size; i++) { cout << ", "; cout << a[i]; } cout << endl; } int ia[] = int ib[] = float fc[] float fd[] {1, 2, 3, 4, {6, 7, 8, 9, = {1.2, 3.4, = {7.8, 9.0, 5}; 0}; 5.6}; 0.1};

#include <iostream.h> template <class T> class Vec { private: int size; T *a; public: Vec(int S, T A[]); ~Vec(); add(const Vec<T> B); void dump(); }; template <class T> Vec<T>::Vec(int S, T A[]) { size = S; a = A; } template <class T> Vec<T>::~Vec() {} template <class T> Vec<T>::add(const Vec<T> B) { int i, min; min = size <= B.size ? size : B.size; for (i = 0; i < min; i++) { a[i] += B.a[i]; } }

void main() { Vec<int> va (5, ia); Vec<int> vb (5, ib); Vec<float> vc (3, fc); Vec<float> vd (3, fd); va.add(vb); va.dump(); vd.add(vc); vd.dump(); }

30

Topics not covered


virtual base class namespace, overloading issues related to

multi inheritance static method const object and volatile object C++ enhancements to union type Overload operator for new delete [] etc

31

Homework
Write a compare function in template.
compare(a, b) return -1 if a<b, 0 if a==b, 1 if a>b test it on at least 4 different types

Write a class FP, fixed-point number


32 bit FP, 16 bit for integer part, 16 bit for fraction support unary + - float, binary + - * /, copy =

Write a class template for complex number


support unary + -, binary + - *, copy = calculate two 8 point sequence FFT, one in FP type, the other in float type.
32

References
C++, 1992 Stanley B. Lippman, Josee Lajoie, Barbara E. Moo, C++ Primer, 4th ed. Addison Wesley Professional, 2005 Anthony Porter, The Best C/C++ Tips Ever, McGraw-Hill 1993.(1995) R. Murray, C++ Strategies and Tactics, Addison Wesley 1993. (2004) B. Kernighan, D. Ritchie, the C Programming Language, 2nd ed, Prentice Hall 1988 (1997)
33

Thank You

34

You might also like