SlideShare ist ein Scribd-Unternehmen logo
1 von 59
Downloaden Sie, um offline zu lesen
from java to c
Mechanism
Exception
Handling
Memory
management
OOP
Function
Pointer
Data
structure
Variable &
constant
Storage class
specifiers
Data type
Package
Java vs. C/C++
Hello world
class HelloWorld
{
public static void main(String args[])
{
System.out.println("Hello World!");
}
}
#include "stdio.h"
void main()
{
printf("Hello World");
}
HelloWorld.java
Anyname.cpp
C/C++
compiler
Building
Java
compiler
Achieve
.jar
.java
.class
Byte
code
javac.exe Prep.
source
.o
Linker
Executable
preprocessor
gcc / g++
cl
gcce/arm
.h
.cpp/.c
Use cpp.exe for
preprocessing if
need
Processor
Running
JVM
OS
C/C++
executable
Java executable
java.exe
Package
Mechanism
Exception
Handling
Memory
management
OOP
FunctionPointer
Data
structure
Variable &
constant
Storage class
specifiers
Data type
Package
package
import
namespace
using namespace
package illustration;
import java.awt.*;
public class Drawing {
. . .
}
using namespace std;
namespace demo
{
class DemoClass
{
…
};
}
Use: ‘ :: ’
<namespace>::<subnamepace>::…::< subnamepace >::<class>::< static properties/functions>
MyNamespace::MyClass::MyStaticFunction()
<namespace>::<subnamepace>::…::< subnamepace >::<var/function>
std::cin
Use: ‘ . ‘ or ‘ -> ’ for accessing class’ properties, fucntions
MyNamespace::MyClass *cA = new MyNamespace::MyClass ()
cA->Foo1();
(*cA).Foo2();
Scope resolution
Use: ‘ . ’
<package>.<subpackage>…<subpackage>.<class>.<properties/functions>
java.lang.Math.abs(a)
. or ->
when & why
Use import for shorten call:
import java.lang.Math;
Math.abs(a);
Use using namespace for shorten call:
using namespace std;
cin >>a;
Data type
Package
Mechanism
Exception
Handling
Memory
management
OOPFunction
Pointer
Data
structure
Variable &
constant
Storage class
specifiers
Primitive Data Types
Java C/C++ (32 bits) Range
void void n/a
char unsigned short / unsigned char 2 bytes / 1 byte
byte char / signed char 1 byte
-128 … 127
short short / short int
signed short
signed short int
2 bytes
-215 … (215 – 1)
int int / signed int
long / long int / signed long / signed long int
4 bytes
-231 … (231 – 1)
long long long / signed long long 8 bytes
-263 … (263 – 1)
boolean bool 1 byte
True/false
float / double float / double 4 bytes/ 8 bytes
Primitive Data Types
• NO “unsigned” (excepted char is an unsigned type)
• Set to “default value” when declare
• Separated to signed & unsigned
• NO “default value”
• No standard string, use char*
Type Range
char • (signed) char: -128 … 127
• unsigned char: 0 … 255
short • (signed) short: -215 … (215 – 1)
• unsigned short: 0 … (216 – 1)
int / long • (signed) int/long: -231 … (231 – 1)
• unsigned int/long: 0 … (232 – 1)
long long • (signed) long long: -263 … (263 – 1)
• usigned long long: 0 … (264 – 1)
C/C++
Use sizeof() to
get size of a type:
char c = 0;
sizeof(c)  1
New type definition
0 C/C++ only
0 Use typedef
typedef int Mytype;
typedef int MyArr[5];
Mytype var1;
MyArr arr;
Storage class
specifiers
Data type
Package
Mechanism
Exception
Handling
Memory
management
OOP
Function
Pointer
Data
structure
Variable &
constant
Storage class specifiers
Key-work Desc. Example
auto Go out of scope once the program exits
from the current block
auto int var1;
int var2;
register Stored in a machine register if possible register int var;
static Allocated when the program begin and
deallocated when the program ends
static int var;
extern Specify that the variable is declared in a
different file. Compiler will not allocate
memory for the variable
extern int DefineElseWhere;
Static / non-static
int m_iVar;
static int s_StaticVar;
Why extern?
0 No need to notify compiler where is the
classes/ variable/ functions
0 MUST notify compiler where is the classes /
variables/ functions were declared
0 Use extern to notify that they were declared
somewhere
Variable &
constant
Storage class
specifiers
Data type
Package
Mechanism
Exception
Handling
Memory
management
OOP
Function
Pointer
Data
structure
Variable
Variable
int todo()
{
unsigned int Age;
float a = 10;
System.out.println(Age);
}
Fail, Age is not set
value before using
int todo()
{
unsigned int Age;
float a = 10;
printf("%d", Age);
}
Age is not set value,
but still OK in C/C++
No default value caused
many mysterious bug
Variable
0 Static duration
static int var2;
struct C
{
void Test(int value)
{
static int var;
cout <<var <<endl;
var = value;
}
};
class MyClass
{
public:
static int s_Var;
};
int MyClass::s_Var = 0;
int main() {
C c1, c2;
c1.Test(100); c2.Test(100);
var2 = 10000;
MyClass::s_Var = 100;
}
Local static
Global static
Set default to zero
var = 0
Value must be set
outside class
definition
Static Class
member
Variable
0 C/C++ only
0 Stored in a machine register if
possible
0 Improve performance
register int index = 0;
Variable
C/C++ only
int globalVar = 0;
int main()
{
int localVar = 10;
cout <<globalVar <<endl;
cout <<localVar <<endl;
}
Constants
Use any where
Use as static data of class
class A
{
final static int k_value = 0;
}
const int A = 0;
Data
structure
Variable &
constant
Storage class
specifiers
Data type
Package
Mechanism
Exception
Handling
Memory
management
OOP
Function
Pointer
Data structure
Data structure
0 Used to set up collections of
named integer constants
enum MyEnumType { ALPHA, BETA, GAMMA };
enum MyEnumType x; /* legal in both C and C++ */
MyEnumType y; // legal only in C++
public enum Day {
SUNDAY, MONDAY, TUESDAY,
WEDNESDAY, THURSDAY,
FRIDAY, SATURDAY
}
Data structure
class JavaClass
{
public JavaClass() {…}
private void Toso() {…}
}
class CClass
{
public:
CClass() {…}
~CClass();
private:
void Toso() ;
};
#include "Any_name.h"
void CClass::Todo()
{
…
}
CClass::~CClass()
{
…
}
JavaClass.java
Any_name.h Other_name.cpp
Data structure
0 C/C++ only
0 A user-defined type that uses same
block of memory for every its list
member.
union NumericType
{
int iValue;
long longValue;
double dValue;
};
int main()
{
union NumericType Values = { 10 };
// iValue = 10
printf_s("%dn", Values.iValue);
Values.dValue = 3.1416;
printf_s("%fn", Values.dValue);
}
0 4 8
iValue
longValue
dValue
Data structure
0 C/C++ only
0 The C++ class is an extension of the C
language structure
0 Default access:
0 Class: private
0 Struct: public
class X {
// private by default
int a;
public:
// public member function
int f() { return a = 5; };
};
struct Y {
// public by default
int f() { return a = 5; };
private:
// private data member
int a;
};
Should be used for storing only.
See more: structure alignment
Pointer
Data
structure
Variable &
constant
Storage class
specifiers
Data type
PackageMechanism
Exception
Handling
Memory
management
OOP
Function
Pointer
0 No explicit pointer in Java
0 Array and object are implicit pointer
0 Explicit null value for array/object
Bicycle bike1 = new Bicycle();
int[] arr = new int [100]
bike1
arr
 Two type of variable:
o Data type
o Pointer type
 Implicit null value, aka zero value (0)
int i;
int *p = &i;
char *st = new char[10];
char *p2 = st;
char st2[] = "ABC“;
char p3[] = st2;
i p st2 = ABC st p2
null
0x0  NULL
sizeof(p) = ?
sizeof(st2) = ?
p = ?
*p = ?
&p = ?
String
0 No standard string in C/C++
0 Use char*, or char[] instead
0 String in C/C++ is array of byte, end with ‘0’
char *st = "String";
S t r i n g 0st
char st2[] = "String";
S t r i n g 0
st2
st = ?
&st = ?
*st = ?
st2 = ?
&st2 = ?
*st2 = ?
Function pointer
0 C/C++ only
0 Is variable store address of a function
// C
void DoIt (float a, char b, char c){……}
void (*pt2Function)(float, char, char) = DoIt;
// using
pt2Function(0, 0, 0);
// C++
class TMyClass
{
public:
void DoIt(float a, char b, char c){……};
};
void (TMyClass::*pt2Member)(float, char, char) = &TMyClass::DoIt;
// using
TMyClass *c = new TMyClass();
(c->*pt2Member)(0, 0, 0);
Object
0 Always use “new”
0 Object variable hold reference
0 Support two kinds:
0 Object variable hold values
0 Object variable hold reference
(through pointer)
Bicycle bike1 = new Bicycle();
bike1.changeCadence(50);
Bicycle bike1;
bike1.changeCadence(50);
Bicycle *bike2 = new Bicycle();
bike2->changeCadence(50);
(*bike2).changeCadence(100);
bike1 vs. bike2?
Function
Pointer
Data
structure
Variable &
constant
Storage class
specifiers
Data typePackage
Mechanism
Exception
Handling
Memory
management
OOP
Function
• Declare inside class
• Pass-by-value only
• No need prototype
• Declare anywhere
• Pass-by-value / pass-by-reference  optional
• Need prototype
How about
array and
object?
Function
0 Function Prototype
void todo();
void main()
{
todo();
}
void todo()
{
……
}
0 Pass by value / Pass by reference
void todo(int pass_by_value, int &pass_by_ref)
“&” is for pass
by reference
prototype
Pass-by-value
void swap1(int i, int j) void swap1(int i, int j)
void swap1(MyClass obj1, MyClass obj2)
swap
A
A’
B’
A
tmp = A;
A = B;
B = tmp
Pass-by-value (2)
A’
B’
A
A
Copy value
(addr. of data)
swap2
void swap2(MyClass obj, MyClass obj2) void swap2(MyClass* obj, MyClass* obj)
tmp = A;
A = B;
B = tmp
Pass-by-ref
void swap3(MyClass &obj1, MyClass &obj2)
Not available
swap
A
A
B
B
tmp = A;
A = B;
B = tmp
OOP
Function
Pointer
Data
structure
Variable &
constant
Storage class
specifiers
Data type
Package
Mechanism
Exception
Handling
Memory
management
OOP
OOP - Inheritance
public class MyDog extends Dog implement ITalkable, ISmileble
{
public:
MyDog(){}
//ITalkable implement
void DoTalk();
//ISmileble
void DoSmile();
void Todo() { super.Todo();}
}
public class MyDog:public Dog,public ITalkable, protected ISmileble
{
public:
MyDog(){}
~MyDog() {}
//ITalkable implement
void DoTalk();
//ISmileble
void DoSmile();
void Todo() { Dog::Todo();}
}
Destructor, called when object is deallocated
OOP
Abstract class vs. Pure virtual class
public abstract class GraphicObject
{
// declare fields
// declare non-abstract methods
abstract void draw();
}
class classname
{
public:
virtual void virtualfunctioname() = 0;
};
Pure virtual function
OOP - virtual
• Function are virtual by default
• Use final to prevent override
• Use key word virtual
virtual int foo()
class ClassA
{
public:
ClassA() {}
virtual void Todo();
};
class ClassB: public ClassA
{
public:
ClassB():ClassA() {}
void Todo();
}
OOP - virtual
class ClassA
{
public:
ClassA() {}
virtual void Todo1() {printf("TodoA1n");}
void Todo2() {printf("TodoA2n");}
};
class ClassB: public ClassA
{
public:
ClassB():ClassA() {}
void Todo1() {printf("TodoB1n");}
void Todo2() {printf("TodoB2n");}
};
void main()
{
ClassA *Obj = new ClassB();
Obj->Todo1();
Obj->Todo2();
}
Output ?
OOP – virtual destructor
class ClassA
{
public:
ClassA() {}
virtual ~ClassA() {printf("DeleteAn");}
};
class ClassB: public ClassA
{
public:
ClassB():ClassA() {}
~ClassB() {printf("DeleteBn");}
};
void main()
{
ClassA *Obj = new ClassB();
delete Obj;
}
Without virtual, only destructor
of ClassA is called
Memory
management
OOP
Function
Pointer
Data
structure
Variable &
constant
Storage class
specifiers
Data type
Package
Mechanism
Exception
Handling
#define NULL 0
int main() {
// Allocate memory for the array
char* pCharArray = new char[100];
// Deallocate memory for the array
delete [] pCharArray;
pCharArray = NULL;
// Allocate memory for the object
CName* pName = new CName;
pName->SetName("John");
// Deallocate memory for the object
delete pName;
pName = NULL;
}
Memory management
Use GC to collect garbage data
• No GC mechanism, handle manually
• Use delete / free to clean up
unused heap
• Memory leak problem
Exception
Handling
Memory
management
OOP
Function
Pointer
Data
structure
Variable &
constant
Storage class
specifiers
Data type
Package
Mechanism
Exception handling
Well supported build in exception
try
{
int zero = 0;
int val = 1/zero;
}
catch (Exception E)
{
E.printStackTrace();
}
Manual exception handling
class DBZEx {};
void div(int num1, int num2)
{
if (num2 == 0) throw (DBZEx ());
}
void main()
{
try
{
div(1, 0);
}
catch (DBZEx ex)
{
printf(" DBZ Exception ");
}
catch (...)
{
printf("Unkown exception");
}
}
The end!
Appendix A: Preprocessor
Appendix A: preprocessor
0 Handle directive: #include
0 Macro definition: #define, #undef
0 Condition inclusion: #if, #ifdef, #ifndef,
#if defined(…), #elif, #else, #endif
0 Refs:
0 http://en.wikipedia.org/wiki/C_preprocessor
0 http://msdn.microsoft.com/en-us/library/b0084kay.aspx
0 http://gcc.gnu.org/onlinedocs/cpp/index.html
0 http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf
Appendix A: preprocessor
#include
0 Include another file.
#include <stdio.h>
int main (void)
{
printf("Hello, world!n");
return 0;
}
The preprocessor replaces the line #include <stdio.h> with the system header file of
that name
Appendix A: preprocessor
#define
0 Define a macro, object-like and function-like
#define Min(x, y) ((x)<(y))?(x):(y)
Object-like #define PI 3.14
Function - like
#define PI 3.14
#define Min(x, y)((x)<(y))?(x):(y)
void main()
{
int pi = PI;
int num = Min(pi, 2);
}
#undef
0 Un-defined a macro
Appendix A: preprocessor
#if, #ifdef, #ifndef, #if defined(…)
#elif, #else,
#endif
0 Directives can be used for conditional compilation.
#ifdef _WIN32
# include <windows.h>
#else
# include <unistd.h>
#endif
#if VERBOSE >= 2
print("trace message");
#endif
#if !defined(WIN32) || defined(__MINGW32__)
...
#endif
Prevent duplicate declaration
void Todo();
//something else
H1.h
#include "H1.h"
//something else
H2.h
#include "H1.h"
#include "H2.h"
//something else
Main.cpp
//from H1
void Todo();
H2.h preprocess
//from H1
void Todo();
//from H2
void Todo();
//something else
Main.cpp preprocess
duplicated
Prevent duplicate declaration
0 Use #ifndef
#ifndef __H1_H__
#define __H1_H__
void Todo();
//something else
#endif
H1.h
#pragma once
void Todo();
//something else
H1.h
0 Use #pragma once

Weitere ähnliche Inhalte

Was ist angesagt?

Javascript engine performance
Javascript engine performanceJavascript engine performance
Javascript engine performanceDuoyi Wu
 
The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)jeffz
 
Splint the C code static checker
Splint the C code static checkerSplint the C code static checker
Splint the C code static checkerUlisses Costa
 
Алексей Кутумов, Вектор с нуля
Алексей Кутумов, Вектор с нуляАлексей Кутумов, Вектор с нуля
Алексей Кутумов, Вектор с нуляSergey Platonov
 
Jscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScriptJscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScriptjeffz
 
Javascript Uncommon Programming
Javascript Uncommon ProgrammingJavascript Uncommon Programming
Javascript Uncommon Programmingjeffz
 
OpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpen Gurukul
 
scala.reflect, Eugene Burmako
scala.reflect, Eugene Burmakoscala.reflect, Eugene Burmako
scala.reflect, Eugene BurmakoVasil Remeniuk
 
Toonz code leaves much to be desired
Toonz code leaves much to be desiredToonz code leaves much to be desired
Toonz code leaves much to be desiredPVS-Studio
 
openFrameworks 007 - 3D
openFrameworks 007 - 3DopenFrameworks 007 - 3D
openFrameworks 007 - 3Droxlu
 
TensorFlow local Python XLA client
TensorFlow local Python XLA clientTensorFlow local Python XLA client
TensorFlow local Python XLA clientMr. Vengineer
 
Дмитрий Демчук. Кроссплатформенный краш-репорт
Дмитрий Демчук. Кроссплатформенный краш-репортДмитрий Демчук. Кроссплатформенный краш-репорт
Дмитрий Демчук. Кроссплатформенный краш-репортSergey Platonov
 
C++11 smart pointer
C++11 smart pointerC++11 smart pointer
C++11 smart pointerLei Yu
 
Bridge TensorFlow to run on Intel nGraph backends (v0.5)
Bridge TensorFlow to run on Intel nGraph backends (v0.5)Bridge TensorFlow to run on Intel nGraph backends (v0.5)
Bridge TensorFlow to run on Intel nGraph backends (v0.5)Mr. Vengineer
 
Understanding Javascript Engines
Understanding Javascript Engines Understanding Javascript Engines
Understanding Javascript Engines Parashuram N
 

Was ist angesagt? (20)

Javascript engine performance
Javascript engine performanceJavascript engine performance
Javascript engine performance
 
The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)
 
Summary of C++17 features
Summary of C++17 featuresSummary of C++17 features
Summary of C++17 features
 
Splint the C code static checker
Splint the C code static checkerSplint the C code static checker
Splint the C code static checker
 
Алексей Кутумов, Вектор с нуля
Алексей Кутумов, Вектор с нуляАлексей Кутумов, Вектор с нуля
Алексей Кутумов, Вектор с нуля
 
Jscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScriptJscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScript
 
Javascript Uncommon Programming
Javascript Uncommon ProgrammingJavascript Uncommon Programming
Javascript Uncommon Programming
 
OpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ Programming
 
scala.reflect, Eugene Burmako
scala.reflect, Eugene Burmakoscala.reflect, Eugene Burmako
scala.reflect, Eugene Burmako
 
Toonz code leaves much to be desired
Toonz code leaves much to be desiredToonz code leaves much to be desired
Toonz code leaves much to be desired
 
Ocl 09
Ocl 09Ocl 09
Ocl 09
 
openFrameworks 007 - 3D
openFrameworks 007 - 3DopenFrameworks 007 - 3D
openFrameworks 007 - 3D
 
Project Roslyn: Exposing the C# and VB compiler’s code analysis
Project Roslyn: Exposing the C# and VB compiler’s code analysisProject Roslyn: Exposing the C# and VB compiler’s code analysis
Project Roslyn: Exposing the C# and VB compiler’s code analysis
 
TensorFlow local Python XLA client
TensorFlow local Python XLA clientTensorFlow local Python XLA client
TensorFlow local Python XLA client
 
Дмитрий Демчук. Кроссплатформенный краш-репорт
Дмитрий Демчук. Кроссплатформенный краш-репортДмитрий Демчук. Кроссплатформенный краш-репорт
Дмитрий Демчук. Кроссплатформенный краш-репорт
 
C++11 smart pointer
C++11 smart pointerC++11 smart pointer
C++11 smart pointer
 
TensorFlow XLA RPC
TensorFlow XLA RPCTensorFlow XLA RPC
TensorFlow XLA RPC
 
Bridge TensorFlow to run on Intel nGraph backends (v0.5)
Bridge TensorFlow to run on Intel nGraph backends (v0.5)Bridge TensorFlow to run on Intel nGraph backends (v0.5)
Bridge TensorFlow to run on Intel nGraph backends (v0.5)
 
OpenCL 3.0 Reference Guide
OpenCL 3.0 Reference GuideOpenCL 3.0 Reference Guide
OpenCL 3.0 Reference Guide
 
Understanding Javascript Engines
Understanding Javascript Engines Understanding Javascript Engines
Understanding Javascript Engines
 

Andere mochten auch

Ekonomika 10-klas-radionova-radchenko
Ekonomika 10-klas-radionova-radchenkoEkonomika 10-klas-radionova-radchenko
Ekonomika 10-klas-radionova-radchenkofreegdz
 
Meninism research
Meninism researchMeninism research
Meninism researchmag_anna
 
Geografiya 6-klas-bojjko
Geografiya 6-klas-bojjkoGeografiya 6-klas-bojjko
Geografiya 6-klas-bojjkofreegdz
 
ульчеко наталья + выставка продажа + воспитанники интерн учреждений
ульчеко наталья + выставка продажа + воспитанники интерн учрежденийульчеко наталья + выставка продажа + воспитанники интерн учреждений
ульчеко наталья + выставка продажа + воспитанники интерн учрежденийNatalia Ul'chenko
 
Android OS
Android OSAndroid OS
Android OSSerhan
 
Francuzka mova-5-klas-klimenko
Francuzka mova-5-klas-klimenkoFrancuzka mova-5-klas-klimenko
Francuzka mova-5-klas-klimenkofreegdz
 
Installation of DSpace, Koha and other software using Liblivecd
Installation of DSpace, Koha and other software using LiblivecdInstallation of DSpace, Koha and other software using Liblivecd
Installation of DSpace, Koha and other software using LiblivecdRupesh Kumar
 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in javalaratechnologies
 
Java interview questions 2
Java interview questions 2Java interview questions 2
Java interview questions 2Sherihan Anver
 
Programming Terminology
Programming TerminologyProgramming Terminology
Programming TerminologyMichael Henson
 
Evaluation question 1
Evaluation question 1 Evaluation question 1
Evaluation question 1 mag_anna
 

Andere mochten auch (14)

19 2016 manuale della sicurezza integrata
19   2016   manuale della sicurezza integrata19   2016   manuale della sicurezza integrata
19 2016 manuale della sicurezza integrata
 
Ekonomika 10-klas-radionova-radchenko
Ekonomika 10-klas-radionova-radchenkoEkonomika 10-klas-radionova-radchenko
Ekonomika 10-klas-radionova-radchenko
 
Fisiologia diapositivas
Fisiologia diapositivasFisiologia diapositivas
Fisiologia diapositivas
 
Meninism research
Meninism researchMeninism research
Meninism research
 
Geografiya 6-klas-bojjko
Geografiya 6-klas-bojjkoGeografiya 6-klas-bojjko
Geografiya 6-klas-bojjko
 
ульчеко наталья + выставка продажа + воспитанники интерн учреждений
ульчеко наталья + выставка продажа + воспитанники интерн учрежденийульчеко наталья + выставка продажа + воспитанники интерн учреждений
ульчеко наталья + выставка продажа + воспитанники интерн учреждений
 
Cuadros guia 3
Cuadros guia 3Cuadros guia 3
Cuadros guia 3
 
Android OS
Android OSAndroid OS
Android OS
 
Francuzka mova-5-klas-klimenko
Francuzka mova-5-klas-klimenkoFrancuzka mova-5-klas-klimenko
Francuzka mova-5-klas-klimenko
 
Installation of DSpace, Koha and other software using Liblivecd
Installation of DSpace, Koha and other software using LiblivecdInstallation of DSpace, Koha and other software using Liblivecd
Installation of DSpace, Koha and other software using Liblivecd
 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in java
 
Java interview questions 2
Java interview questions 2Java interview questions 2
Java interview questions 2
 
Programming Terminology
Programming TerminologyProgramming Terminology
Programming Terminology
 
Evaluation question 1
Evaluation question 1 Evaluation question 1
Evaluation question 1
 

Ähnlich wie from java to c

Learning Java 1 – Introduction
Learning Java 1 – IntroductionLearning Java 1 – Introduction
Learning Java 1 – Introductioncaswenson
 
11 lec 11 storage class
11 lec 11 storage class11 lec 11 storage class
11 lec 11 storage classkapil078
 
Getting Started Cpp
Getting Started CppGetting Started Cpp
Getting Started CppLong Cao
 
Chapter i(introduction to java)
Chapter i(introduction to java)Chapter i(introduction to java)
Chapter i(introduction to java)Chhom Karath
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Chris Adamson
 
How to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeHow to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeMicrosoft Tech Community
 
How to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeHow to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeMicrosoft Tech Community
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentalsHCMUTE
 
Welcome to Modern C++
Welcome to Modern C++Welcome to Modern C++
Welcome to Modern C++Seok-joon Yun
 
Binary patching for fun and profit @ JUG.ru, 25.02.2012
Binary patching for fun and profit @ JUG.ru, 25.02.2012Binary patching for fun and profit @ JUG.ru, 25.02.2012
Binary patching for fun and profit @ JUG.ru, 25.02.2012Anton Arhipov
 

Ähnlich wie from java to c (20)

C++ theory
C++ theoryC++ theory
C++ theory
 
Learning Java 1 – Introduction
Learning Java 1 – IntroductionLearning Java 1 – Introduction
Learning Java 1 – Introduction
 
11 lec 11 storage class
11 lec 11 storage class11 lec 11 storage class
11 lec 11 storage class
 
Storage class in C Language
Storage class in C LanguageStorage class in C Language
Storage class in C Language
 
srgoc
srgocsrgoc
srgoc
 
Getting Started Cpp
Getting Started CppGetting Started Cpp
Getting Started Cpp
 
C++ Language
C++ LanguageC++ Language
C++ Language
 
Chapter i(introduction to java)
Chapter i(introduction to java)Chapter i(introduction to java)
Chapter i(introduction to java)
 
C# 6.0 Preview
C# 6.0 PreviewC# 6.0 Preview
C# 6.0 Preview
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
 
How to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeHow to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ Code
 
How to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeHow to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ Code
 
OOC MODULE1.pptx
OOC MODULE1.pptxOOC MODULE1.pptx
OOC MODULE1.pptx
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 
Welcome to Modern C++
Welcome to Modern C++Welcome to Modern C++
Welcome to Modern C++
 
Apache Thrift
Apache ThriftApache Thrift
Apache Thrift
 
Lecture4
Lecture4Lecture4
Lecture4
 
Lecture4
Lecture4Lecture4
Lecture4
 
Binary patching for fun and profit @ JUG.ru, 25.02.2012
Binary patching for fun and profit @ JUG.ru, 25.02.2012Binary patching for fun and profit @ JUG.ru, 25.02.2012
Binary patching for fun and profit @ JUG.ru, 25.02.2012
 
Dr archana dhawan bajaj - c# dot net
Dr archana dhawan bajaj - c# dot netDr archana dhawan bajaj - c# dot net
Dr archana dhawan bajaj - c# dot net
 

Kürzlich hochgeladen

UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1DianaGray10
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemAsko Soukka
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAshyamraj55
 
RAG Patterns and Vector Search in Generative AI
RAG Patterns and Vector Search in Generative AIRAG Patterns and Vector Search in Generative AI
RAG Patterns and Vector Search in Generative AIUdaiappa Ramachandran
 
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...Aggregage
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfinfogdgmi
 
Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024D Cloud Solutions
 
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IES VE
 
Cloud Revolution: Exploring the New Wave of Serverless Spatial Data
Cloud Revolution: Exploring the New Wave of Serverless Spatial DataCloud Revolution: Exploring the New Wave of Serverless Spatial Data
Cloud Revolution: Exploring the New Wave of Serverless Spatial DataSafe Software
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureEric D. Schabell
 
Things you didn't know you can use in your Salesforce
Things you didn't know you can use in your SalesforceThings you didn't know you can use in your Salesforce
Things you didn't know you can use in your SalesforceMartin Humpolec
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsSeth Reyes
 
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostKubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostMatt Ray
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6DianaGray10
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfDianaGray10
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfAijun Zhang
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintMahmoud Rabie
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Adtran
 
Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.YounusS2
 
GenAI and AI GCC State of AI_Object Automation Inc
GenAI and AI GCC State of AI_Object Automation IncGenAI and AI GCC State of AI_Object Automation Inc
GenAI and AI GCC State of AI_Object Automation IncObject Automation
 

Kürzlich hochgeladen (20)

UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystem
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
 
RAG Patterns and Vector Search in Generative AI
RAG Patterns and Vector Search in Generative AIRAG Patterns and Vector Search in Generative AI
RAG Patterns and Vector Search in Generative AI
 
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdf
 
Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024
 
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
 
Cloud Revolution: Exploring the New Wave of Serverless Spatial Data
Cloud Revolution: Exploring the New Wave of Serverless Spatial DataCloud Revolution: Exploring the New Wave of Serverless Spatial Data
Cloud Revolution: Exploring the New Wave of Serverless Spatial Data
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability Adventure
 
Things you didn't know you can use in your Salesforce
Things you didn't know you can use in your SalesforceThings you didn't know you can use in your Salesforce
Things you didn't know you can use in your Salesforce
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and Hazards
 
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostKubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdf
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership Blueprint
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™
 
Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.
 
GenAI and AI GCC State of AI_Object Automation Inc
GenAI and AI GCC State of AI_Object Automation IncGenAI and AI GCC State of AI_Object Automation Inc
GenAI and AI GCC State of AI_Object Automation Inc
 

from java to c

  • 4. Hello world class HelloWorld { public static void main(String args[]) { System.out.println("Hello World!"); } } #include "stdio.h" void main() { printf("Hello World"); } HelloWorld.java Anyname.cpp
  • 8. Package package import namespace using namespace package illustration; import java.awt.*; public class Drawing { . . . } using namespace std; namespace demo { class DemoClass { … }; }
  • 9. Use: ‘ :: ’ <namespace>::<subnamepace>::…::< subnamepace >::<class>::< static properties/functions> MyNamespace::MyClass::MyStaticFunction() <namespace>::<subnamepace>::…::< subnamepace >::<var/function> std::cin Use: ‘ . ‘ or ‘ -> ’ for accessing class’ properties, fucntions MyNamespace::MyClass *cA = new MyNamespace::MyClass () cA->Foo1(); (*cA).Foo2(); Scope resolution Use: ‘ . ’ <package>.<subpackage>…<subpackage>.<class>.<properties/functions> java.lang.Math.abs(a) . or -> when & why Use import for shorten call: import java.lang.Math; Math.abs(a); Use using namespace for shorten call: using namespace std; cin >>a;
  • 11. Primitive Data Types Java C/C++ (32 bits) Range void void n/a char unsigned short / unsigned char 2 bytes / 1 byte byte char / signed char 1 byte -128 … 127 short short / short int signed short signed short int 2 bytes -215 … (215 – 1) int int / signed int long / long int / signed long / signed long int 4 bytes -231 … (231 – 1) long long long / signed long long 8 bytes -263 … (263 – 1) boolean bool 1 byte True/false float / double float / double 4 bytes/ 8 bytes
  • 12. Primitive Data Types • NO “unsigned” (excepted char is an unsigned type) • Set to “default value” when declare • Separated to signed & unsigned • NO “default value” • No standard string, use char* Type Range char • (signed) char: -128 … 127 • unsigned char: 0 … 255 short • (signed) short: -215 … (215 – 1) • unsigned short: 0 … (216 – 1) int / long • (signed) int/long: -231 … (231 – 1) • unsigned int/long: 0 … (232 – 1) long long • (signed) long long: -263 … (263 – 1) • usigned long long: 0 … (264 – 1) C/C++ Use sizeof() to get size of a type: char c = 0; sizeof(c)  1
  • 13. New type definition 0 C/C++ only 0 Use typedef typedef int Mytype; typedef int MyArr[5]; Mytype var1; MyArr arr;
  • 15. Storage class specifiers Key-work Desc. Example auto Go out of scope once the program exits from the current block auto int var1; int var2; register Stored in a machine register if possible register int var; static Allocated when the program begin and deallocated when the program ends static int var; extern Specify that the variable is declared in a different file. Compiler will not allocate memory for the variable extern int DefineElseWhere; Static / non-static int m_iVar; static int s_StaticVar;
  • 16. Why extern? 0 No need to notify compiler where is the classes/ variable/ functions 0 MUST notify compiler where is the classes / variables/ functions were declared 0 Use extern to notify that they were declared somewhere
  • 17. Variable & constant Storage class specifiers Data type Package Mechanism Exception Handling Memory management OOP Function Pointer Data structure
  • 19. Variable int todo() { unsigned int Age; float a = 10; System.out.println(Age); } Fail, Age is not set value before using int todo() { unsigned int Age; float a = 10; printf("%d", Age); } Age is not set value, but still OK in C/C++ No default value caused many mysterious bug
  • 20. Variable 0 Static duration static int var2; struct C { void Test(int value) { static int var; cout <<var <<endl; var = value; } }; class MyClass { public: static int s_Var; }; int MyClass::s_Var = 0; int main() { C c1, c2; c1.Test(100); c2.Test(100); var2 = 10000; MyClass::s_Var = 100; } Local static Global static Set default to zero var = 0 Value must be set outside class definition Static Class member
  • 21. Variable 0 C/C++ only 0 Stored in a machine register if possible 0 Improve performance register int index = 0;
  • 22. Variable C/C++ only int globalVar = 0; int main() { int localVar = 10; cout <<globalVar <<endl; cout <<localVar <<endl; }
  • 23. Constants Use any where Use as static data of class class A { final static int k_value = 0; } const int A = 0;
  • 24. Data structure Variable & constant Storage class specifiers Data type Package Mechanism Exception Handling Memory management OOP Function Pointer
  • 26. Data structure 0 Used to set up collections of named integer constants enum MyEnumType { ALPHA, BETA, GAMMA }; enum MyEnumType x; /* legal in both C and C++ */ MyEnumType y; // legal only in C++ public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }
  • 27. Data structure class JavaClass { public JavaClass() {…} private void Toso() {…} } class CClass { public: CClass() {…} ~CClass(); private: void Toso() ; }; #include "Any_name.h" void CClass::Todo() { … } CClass::~CClass() { … } JavaClass.java Any_name.h Other_name.cpp
  • 28. Data structure 0 C/C++ only 0 A user-defined type that uses same block of memory for every its list member. union NumericType { int iValue; long longValue; double dValue; }; int main() { union NumericType Values = { 10 }; // iValue = 10 printf_s("%dn", Values.iValue); Values.dValue = 3.1416; printf_s("%fn", Values.dValue); } 0 4 8 iValue longValue dValue
  • 29. Data structure 0 C/C++ only 0 The C++ class is an extension of the C language structure 0 Default access: 0 Class: private 0 Struct: public class X { // private by default int a; public: // public member function int f() { return a = 5; }; }; struct Y { // public by default int f() { return a = 5; }; private: // private data member int a; }; Should be used for storing only. See more: structure alignment
  • 30. Pointer Data structure Variable & constant Storage class specifiers Data type PackageMechanism Exception Handling Memory management OOP Function
  • 31. Pointer 0 No explicit pointer in Java 0 Array and object are implicit pointer 0 Explicit null value for array/object Bicycle bike1 = new Bicycle(); int[] arr = new int [100] bike1 arr  Two type of variable: o Data type o Pointer type  Implicit null value, aka zero value (0) int i; int *p = &i; char *st = new char[10]; char *p2 = st; char st2[] = "ABC“; char p3[] = st2; i p st2 = ABC st p2 null 0x0  NULL sizeof(p) = ? sizeof(st2) = ? p = ? *p = ? &p = ?
  • 32. String 0 No standard string in C/C++ 0 Use char*, or char[] instead 0 String in C/C++ is array of byte, end with ‘0’ char *st = "String"; S t r i n g 0st char st2[] = "String"; S t r i n g 0 st2 st = ? &st = ? *st = ? st2 = ? &st2 = ? *st2 = ?
  • 33. Function pointer 0 C/C++ only 0 Is variable store address of a function // C void DoIt (float a, char b, char c){……} void (*pt2Function)(float, char, char) = DoIt; // using pt2Function(0, 0, 0); // C++ class TMyClass { public: void DoIt(float a, char b, char c){……}; }; void (TMyClass::*pt2Member)(float, char, char) = &TMyClass::DoIt; // using TMyClass *c = new TMyClass(); (c->*pt2Member)(0, 0, 0);
  • 34. Object 0 Always use “new” 0 Object variable hold reference 0 Support two kinds: 0 Object variable hold values 0 Object variable hold reference (through pointer) Bicycle bike1 = new Bicycle(); bike1.changeCadence(50); Bicycle bike1; bike1.changeCadence(50); Bicycle *bike2 = new Bicycle(); bike2->changeCadence(50); (*bike2).changeCadence(100); bike1 vs. bike2?
  • 35. Function Pointer Data structure Variable & constant Storage class specifiers Data typePackage Mechanism Exception Handling Memory management OOP
  • 36. Function • Declare inside class • Pass-by-value only • No need prototype • Declare anywhere • Pass-by-value / pass-by-reference  optional • Need prototype How about array and object?
  • 37. Function 0 Function Prototype void todo(); void main() { todo(); } void todo() { …… } 0 Pass by value / Pass by reference void todo(int pass_by_value, int &pass_by_ref) “&” is for pass by reference prototype
  • 38. Pass-by-value void swap1(int i, int j) void swap1(int i, int j) void swap1(MyClass obj1, MyClass obj2) swap A A’ B’ A tmp = A; A = B; B = tmp
  • 39. Pass-by-value (2) A’ B’ A A Copy value (addr. of data) swap2 void swap2(MyClass obj, MyClass obj2) void swap2(MyClass* obj, MyClass* obj) tmp = A; A = B; B = tmp
  • 40. Pass-by-ref void swap3(MyClass &obj1, MyClass &obj2) Not available swap A A B B tmp = A; A = B; B = tmp
  • 41. OOP Function Pointer Data structure Variable & constant Storage class specifiers Data type Package Mechanism Exception Handling Memory management
  • 42. OOP
  • 43. OOP - Inheritance public class MyDog extends Dog implement ITalkable, ISmileble { public: MyDog(){} //ITalkable implement void DoTalk(); //ISmileble void DoSmile(); void Todo() { super.Todo();} } public class MyDog:public Dog,public ITalkable, protected ISmileble { public: MyDog(){} ~MyDog() {} //ITalkable implement void DoTalk(); //ISmileble void DoSmile(); void Todo() { Dog::Todo();} } Destructor, called when object is deallocated
  • 44. OOP Abstract class vs. Pure virtual class public abstract class GraphicObject { // declare fields // declare non-abstract methods abstract void draw(); } class classname { public: virtual void virtualfunctioname() = 0; }; Pure virtual function
  • 45. OOP - virtual • Function are virtual by default • Use final to prevent override • Use key word virtual virtual int foo() class ClassA { public: ClassA() {} virtual void Todo(); }; class ClassB: public ClassA { public: ClassB():ClassA() {} void Todo(); }
  • 46. OOP - virtual class ClassA { public: ClassA() {} virtual void Todo1() {printf("TodoA1n");} void Todo2() {printf("TodoA2n");} }; class ClassB: public ClassA { public: ClassB():ClassA() {} void Todo1() {printf("TodoB1n");} void Todo2() {printf("TodoB2n");} }; void main() { ClassA *Obj = new ClassB(); Obj->Todo1(); Obj->Todo2(); } Output ?
  • 47. OOP – virtual destructor class ClassA { public: ClassA() {} virtual ~ClassA() {printf("DeleteAn");} }; class ClassB: public ClassA { public: ClassB():ClassA() {} ~ClassB() {printf("DeleteBn");} }; void main() { ClassA *Obj = new ClassB(); delete Obj; } Without virtual, only destructor of ClassA is called
  • 49. #define NULL 0 int main() { // Allocate memory for the array char* pCharArray = new char[100]; // Deallocate memory for the array delete [] pCharArray; pCharArray = NULL; // Allocate memory for the object CName* pName = new CName; pName->SetName("John"); // Deallocate memory for the object delete pName; pName = NULL; } Memory management Use GC to collect garbage data • No GC mechanism, handle manually • Use delete / free to clean up unused heap • Memory leak problem
  • 51. Exception handling Well supported build in exception try { int zero = 0; int val = 1/zero; } catch (Exception E) { E.printStackTrace(); } Manual exception handling class DBZEx {}; void div(int num1, int num2) { if (num2 == 0) throw (DBZEx ()); } void main() { try { div(1, 0); } catch (DBZEx ex) { printf(" DBZ Exception "); } catch (...) { printf("Unkown exception"); } }
  • 54. Appendix A: preprocessor 0 Handle directive: #include 0 Macro definition: #define, #undef 0 Condition inclusion: #if, #ifdef, #ifndef, #if defined(…), #elif, #else, #endif 0 Refs: 0 http://en.wikipedia.org/wiki/C_preprocessor 0 http://msdn.microsoft.com/en-us/library/b0084kay.aspx 0 http://gcc.gnu.org/onlinedocs/cpp/index.html 0 http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf
  • 55. Appendix A: preprocessor #include 0 Include another file. #include <stdio.h> int main (void) { printf("Hello, world!n"); return 0; } The preprocessor replaces the line #include <stdio.h> with the system header file of that name
  • 56. Appendix A: preprocessor #define 0 Define a macro, object-like and function-like #define Min(x, y) ((x)<(y))?(x):(y) Object-like #define PI 3.14 Function - like #define PI 3.14 #define Min(x, y)((x)<(y))?(x):(y) void main() { int pi = PI; int num = Min(pi, 2); } #undef 0 Un-defined a macro
  • 57. Appendix A: preprocessor #if, #ifdef, #ifndef, #if defined(…) #elif, #else, #endif 0 Directives can be used for conditional compilation. #ifdef _WIN32 # include <windows.h> #else # include <unistd.h> #endif #if VERBOSE >= 2 print("trace message"); #endif #if !defined(WIN32) || defined(__MINGW32__) ... #endif
  • 58. Prevent duplicate declaration void Todo(); //something else H1.h #include "H1.h" //something else H2.h #include "H1.h" #include "H2.h" //something else Main.cpp //from H1 void Todo(); H2.h preprocess //from H1 void Todo(); //from H2 void Todo(); //something else Main.cpp preprocess duplicated
  • 59. Prevent duplicate declaration 0 Use #ifndef #ifndef __H1_H__ #define __H1_H__ void Todo(); //something else #endif H1.h #pragma once void Todo(); //something else H1.h 0 Use #pragma once

Hinweis der Redaktion

  1. 1. Pre-process: First the C pre-processor (cpp.exe) is run on each source (.cpp) file. This interprets pre-processor directives, which are indicated by the # symbol. The output of the preprocessor will be files containing C++ code. 2. Compile: The expanded source code file resulting from pre-processing is compiled to produce an object file (suffix .obj or .o) containing the raw machine instructions. Linking: The Linker (Loader) combines one or more object files together with standard libraries (which contain collections of object files), solving all the external references to produce an executable (suffix .exe or no suffix) are solved. This is the program that one actually runs. The objects files are program modules containing machine code and information for the linker
  2. Storage class specifiers tell the compiler the duration and visibility of the object or function they declared as well as where an object be stored
  3. Static duration means that the object or variable is allocated when the program starts and is deallocated when the program ends