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

1

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

replace malloc/free p = new type. delete [] p. // definition // definition // reference 3 What's new or improved in C++ • new/delete.What's new or improved in C++ • Comments. // call 4 . // ☺ ref must be initialized • function with ref arguments • function return ref. extern int b. // array • reference. // scalar p = new type [size]. a very safe replacement for pointer int & a. get from STDIN cin >> a >> b. int b. // get two input and store in a and b • Type cast. // wrong int & a = b. both (type) expr and type(expr) • auto. delete p.h> send to STDOUT cout << "Hello world!" << j << x + 1 << endl. Can be used as lvalue expression int & index(int i) { return a[i]. don't return a ref to auto variable. static in globel scope extern int b = 5.} // define index(9) = 5. both /* */ and line comments // • <iostream. static inside function scope extern.h> instead of <stdio.

• func def: • func: int *pf(int. 5 What's new or improved in C++ • inline function. and returns a pointer to int.• func P: int (*pf)(int.Review Pointer • a scalar: int a. each element is a pointer to function. pf is a pointer to function. • func P: int *(*pf)(int. replacement of MACRO inline int isnumber(char c) { return (c >= '0' && c <= '9') ? 1 : 0. int a (int. the function takes two int type arguments. int). array of two element. • P to scalar: int * pa. int). define the body of inline function before calling. not linked with your code later. returns a pointer to int • What about this one: int *(*p[2])(int. The function takes two int type arguments. int). int). } … if (isnumber(c)) { … } else { … } • inline function will be compiled into your code. 6 . int).

etc It's safer to use function with default argument. num). va_start. // so far so good void fun(int i).h> int max(int n. 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. • Variable arguments #include <stdarg.1234. int=-1.… study the stdarg. 8 . and learn how to use va_list. va_start(ap. int num…) { va_list ap. int max(int=-1. va_end. } • avoid ambiguous definitions void fun(int a. va_arg. // wrong. count << abs(a) << newl << abs(l) << newl << abs(f) << newl. float f = -0. int b=4). int=-1.h. long l = 0xfffff. int=-1).What's new or improved in C++ • Default arguments Arguments can has their default values.

int len.len *ps->buffer // i. (*ps). • private vs.e. but all data and methods are public by default.Structure • structure in C++ is similar to class. address of ps->len 9 Class • Class and object. ps->len // i. } myStruct s. pointer to object • object data. public 10 . ++(ps->buffer) (++ps)->buffer // ++ps.e.e. then ps->buffer *++ps->buffer //++(ps->buffer). typedef myStruct { int * buffer. set / get 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. *(ps->buffer) ++ps->buffer // i. get point ++*ps->buffer //inc the variable ps->buffer points to &ps->len // i.e. object method. method arguments can contians default values Protect the object data. myStruct *ps.

*q. Inside the body of a method. Point::Point(int iX. you can refer to the this pointer. "this" is a hidden pointer points to the object calling the method. int iY) { x = iX.} int X(int iX) {int oX=x. x=iX. } //Point:: select a correct scope Point::~Point() { . Method can be overloaded.x. y. // virtual X::~X() int X() {return x. void main() { p = new Point(1.2). etc • Class with two private data. 11 Copy Constructor • Construct a new object by existing ones. Point::Point(const Point &P) { x = P. 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. Constructor. return oY.} // define inline method int Y(int). } . q = new Point(*p). y = iY. not even void.2). class Point { … Point(const Point &). return oX./*Do nothing*/ } // never call exit() in destructors inline Point::Y(int y) { int oY=this->y. cout << q->X() << '.} int Y() {return y. // X::X(const X&) … }. // X::X(??? ) virtual ~Point(). } … Point *p. this->y=y. Arguments may take default values. } 12 . void main() { p = new Point(1. y = P. cout << p->X() << '. }.y.Sample Class. public: Point(int iX=0. since y > p p->x.' << q->Y() << endl. int iY=0).' << p->Y(). and set/get methods class Point { private: int x. inline method can be defined inside or outside class body. } Point *p.

cout << a[1]. 6}. 2). } // must avoid self-assignments return *this. cout << Q. Q.X() << '. 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).Y() << endl. // const X& X::operator=(const X&) }.2). Q = Q. } • Don't rely on any C++ default copy method.' << a[0]. R.' << Q.' << S. const Point& Point::operator=(const Point& P) { if (&P != this) { x = P. // return type is const & so that this line won't be parsed as (S = R) = Q cout << S. Point(3.y. y = P.e. overload the default '=' operator Very similar to constructors. S.X() << '.Y() << endl.' << Q.Y() << endl. cout << Q.' << a[2].x.Copy method • • • copy method is called when doing P1 = P2. but shall return a value. 4)}. Point(1.X() << '. you can't initialize a Point object in this way: … Point b = {5.Y() << endl.X() << '. cout << a[2]. void main() { cout << a[0].X() << '.X() << '.Y() << endl.' << a[1].Y() << endl. // Wrong 14 . } Point *p. void main() { p = new Point(1. } • Since the data of Point is private. S = R = Q. Q = *p. i. Remember the example of deep-copy in SysVlog? 13 Array of objects • Initialize array of objects with initialize-list … Point a[] = {Point().

' << a. // here we have some object inside another object public: Line(int sX=0.' << a. const Point & Line::Start(const Point & Point *pS = new Point(s). a = 6. cout << S. // Normal case cout << a. eY) {} Line::Line(const Point &S.8. int sY. Point S = L. int iY) : x(iX). sY). int eY=0).7. } } S) { // can't say Point oS(s).Y() << endl. change the type of (T1.X() << '. const Point & Start(const Point &).X() << '. // const Point & End(const Point &).) to X 15 Have objects as object member? Object members constructed in declare order. same as (Point)7 cout << a. class Line { private: Point s.Start().X() << '. y(iY) {} 16 .Constructor as type cast function • Constructor will be called automatically void main() { Point a(5). } • Also valid for non-class type data: Point::Point(int iX. int eX=0. 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 &E). int eY) : s(sX. virtual ~Line(). T2. …).Y() << endl.// type case. int eX. // const Point & End(). Line::Line(int sX. return *pS.Y() << endl. and destructed in the reverse order. // 6 is type-casted to Point cout << a. a = Point(7).' << S. const Point &E) : s(S). return oS. // can't return a ref to local variables void main() { Line L(6. }. } • X::X(T1. …. e(eX. Line(const Point &S. int sY=0.. e. s = S.X() << '. T2.9).' << a.Y() << endl. const Point & Start().

private Base2 { … Derived(arg_list). … Derived(arg_list). • The default label is private for derived class. all public member of Base also becomes private in Derived. and is public for derived structure 17 Constructor of Derived • Constructor of Base will be called first. member1(arg1). member2(arg2). But not Derived friends and ordinary users. then constructors of member objects class Derived : public Base { classX member1. classY member2. all "protected" member of Base are accessible by Base members and friends. … } // acc_label is either public or private Derived::Derived(arg_list) :Base(arg).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. Base2(arg) … { /* body */ } 18 . } // acc_label is either public or private Derived::Derived(arg_list) :Base1(arg). and by Derived members.… { // body of constructor } • For multiple inheritance. • If access label is private. put all base constructors in the list class Derived : public Base1. • If access label is public all public member of Base are still public.

Base { func(int. since protected member can be access from methods in derived class.func(0). // calls Base::func D.func(0. It's called abstract class • You still can make derived class from am abstract class. // ok: calls Base::func 20 . B. // hides func in the Base Base B. no object can be instanciated from the class. Derived D.func(0.'protected' and abstract class • A 'protected' member can't be access from outside • When all constructors are labeled protected.Base::func(0. class int }. // calls Derived::func D. 0). 0). int). // error: func with two arguments is hidden D. 19 Method hidden class int }. Derived : public Base { funt(int). 0).

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

this->CD. • A class containing (or inheriting) one or more pure virtual functions is an abstract base class.. • Derived class shall implement the pure virtual function.in your method. ..Pure Virtual Function • Virtual function without a body (who's body is defined as '=0') is a pure virtual function. } static int X::CD=5. 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. X::CD++. // this is only a reference // define with initial value // access class data // class data has no this pointer 24 . class Base{ … virtual int Area() = 0. } • Never call pure virtual function directly.

class B.} class B {… friend int A::func(B&). } 25 type cast • type cast a class to another type ( along with modifiers like * [] () const volatile etc) class X { operator type ().} 26 .friend function • Class can declare some functions to be friend.} class X { virtual operator type (). Or other class as friend. class A {public: int func(B&). class C. friend class C. 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.

} void main() { int a. .h> template <typename T> T abs(const T &var) { return (var >= 0) ? var : -var. 2). } 27 Function Template • Generic Programming writing code that's independent of any particular type #include <iostream. a = -5.y. friend Point operator+ (const Point &. " << abs(b) << endl. x = a. const Point &b) { int x. 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.x. .A + B. 12 41.4 52 25. C. Point Point::operator .X() << ". 8). return Point(x. " << C.* :: ?: Can be virtual. -y).overload the operators • Redefine C++ operators For all existing operators. cout << abs(a) << ". 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 . b = -123.(). cout << abs<signed char>(-60) << ". " << sqr(b) << endl.456 5. } Point operator+ (const Point &a. const Point &). C = . 1 <. int a bs(float) a float plate try tem 3. 60 n m e ca i t e m e f or iler so Comp a proper typ set e an deduc e.Y() << endl. y). cout << sqr(a) << ".456. cout << C. y = a.y + b. rload? e v o g … sin Still u bs(int). float b. " << abs<long>(-60) << endl. } void main() { Point A(1. y. B(5.() { return Point(-x. Or user c e> at templ ly via <typ al m an u 28 . except .x + b. } • sqr() can work on any class type when * is overloaded. } Can name. }.

8. fc). int i. 3. 0}.6}. add(const Vec<T> B). Vec<int> vb (5. } 29 Class with template • When using a class template. fd). ib).Nontype template parameter • nontype parameter in template #include <iostream. int> (a) << endl. 3. i < N.-1.1}. i++) { cout << ". ~Vec(). void dump(). 9. = {7.dump(). 5. for (i = 1. va. } int a[] = {1. = {1. 5}. public: Vec(int S. a = A. } template <class T> Vec<T>::~Vec() {} template <class T> Vec<T>::add(const Vec<T> B) { int i. T A[]) { size = S. min. T A[]).size. 4. {6. ia).8. } } void main() { Vec<int> va (5. } 30 . we must specify a valid type for the template parameter.a[i]. min = size <= B.-3}. vd. 9. cout << a[0]. typename T> T max(T var[N]) { T ans. va. for (i = 0.2. }.add(vc). #include <iostream.3. for (i = 1.2.dump(). Vec<float> vd (3.} } return ans. 0. ". i++) { if (ans < var[i]) {ans = var[i]. ans = var[0]. 2. template <class T> void Vec<T>::dump() { int i.h> template <size_t N. vd.4.-2.size ? size : B. T *a. i < min. 7.add(vb). } cout << endl. void main() { cout << max<7.h> template <class T> class Vec { private: int size. cout << a[i]. i++) { a[i] += B.4. i < size. } int ia[] = int ib[] = float fc[] float fd[] {1. Vec<float> vc (3.0. template <class T> Vec<T>::Vec(int S.

16 bit for fraction support unary + . copy = calculate two 8 point sequence FFT. 0 if a==b. 32 . 16 bit for integer part. copy = • Write a class template for complex number support unary + -. fixed-point number 32 bit FP. one in FP type. binary + .Topics not covered • virtual base class • namespace. 1 if a>b test it on at least 4 different types • Write a class FP.float.* /.*. the other in float type. 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. binary + . b) return -1 if a<b. compare(a.

The Best C/C++ Tips Ever. Kernighan. 2005 • Anthony Porter. Murray. (王昕译,中国电力出版社2004) • B.References • 张国锋 C++语言及其程序设计教程. Moo. 4th ed. Josee Lajoie. D. Prentice Hall 1988 (清华大学出版社1997影印版) 33 Thank You 34 .(秦冬雷等译,电子工业出版社1995) • R. the C Programming Language. Barbara E. Ritchie. 2nd ed. Addison Wesley Professional. Addison Wesley 1993. McGraw-Hill 1993. C++ Strategies and Tactics. C++ Primer. Lippman. 电子工业出版社1992 • Stanley B.