Differences between struct and class

Source: Internet
Author: User

1. Differences between classes and struct in C ++

A: The default access permission of class members is private, and the default access permission of structure members is public, which is identical in other places.

---------------------------------------------------------------------------

2. Private inheritance

Private inheritance is actually similar to a combination. It should be said that it is a design concept rather than a specific implementation concept. In specific implementations, private inheritance is rarely used because the combination is clearer in most cases.

Public inheritance means is-a, private inheritance means is-implemented-in-terms-of (implemented according ).

Reference: C ++ proverbs: careful use of private inheritance

Http://tech.163.com/05/1124/14/23B2S17F0009159Q.html

---------------------------------------------------------------------------

3. Write the output of the following program.

# Include <stdio. h>

Class ABC;

Void del (ABC * pobj)

{

Delete pobj;

}

Class ABC

{

Public:

ABC (){

Printf ("ABC/R/N ");

}

~ ABC (){

Printf ("~ ABC/R/N ");

}

};

Int main (INT argc, char * argv [])

{

ABC * pobj = new ABC;

Del (pobj );

}

A:

ABC

Note: ABC's destructor are not defined when del functions are defined, so they are not called.

---------------------------------------------------------------------------

4. Write the output of the following program.

# Include <stdio. h>

# Include <stdlib. h>

Void * operator new (size_t size)

{

Printf ("malloc % u/R/N", size );

Return malloc (size );

}

Void operator Delete (void * memblock)

{

Printf ("Free/R/N ");

Return free (memblock );

}

Class ABC

{

Public:

ABC ()

{

Printf ("ABC/R/N ");

Throw int ();

}

~ ABC ()

{

Printf ("~ ABC/R/N ");

}

};

Int main (INT argc, char * argv [])

{

Try

{

New ABC;

}

Catch (Int & I)

{

Printf ("% d/R/N", I );

}

Return 0;

}

A:

Malloc 1

ABC

Free

0

If you replace "new ABC;" with "abc a;", the result will be:

ABC

0

Note:

1. In C ++, the constructor does not trigger the calling of the Destructor after throwing an exception, which is different from the Object Pascal. C ++ believes that the failed construction means that the object is not generated, and it will not die if it is not generated. However, when the constructor throws an exception, the delete function is still called to release the memory.

Operator new reloads global new, so the new will certainly call the operator new during the following construction. Operator Delete is the same. Therefore, malloc 1 is output first.

After the new memory is allocated, the constructor is automatically called, so ABC is output.

Throw an exception in the constructor, throw int ();

This exception is captured and the output I value is 0.

However, the memory must be released before the captured exceptions are processed. Due to an exception or error, the new memory allocation has been completed. If the delete operation is not performed, the memory will be leaked.

2. When a stack object is generated, the operator new and operator Delete automatically called by C ++ are global operator new and operator Delete.

Refer:

More effective C ++ clause 10: preventing resource leakage in Constructors

...... Do not worry about non-pointer data members in the bookentry. Data members are automatically initialized before the class constructor is called. So if
The bookentry constructor starts execution. The thename, theaddress, and thephones of the object
The data member has been fully constructed. These data can be viewed as fully constructed objects, so they will be automatically released without your intervention .......

---------------------------------------------------------------------------

5. Write the output of the following program.

# Include <stdio. h>

Template <typename T>

Class ABC {

Public:

ABC (){

Printf ("Primary/R/N ");

}

};

Template <>

ABC <int>: ABC ()

{

Printf ("member spec/R/N ");

};

Template <typename T, typename P>

Class ABC <t (*) (p)>

{

Public:

ABC (){

Printf ("partial spec/R/N ");

}

};

Int main (INT argc, char * argv [])

{

ABC <void * (*) (INT)> f_abc;

ABC <int> I _abc;

}

A:

Partial spec

Member spec

Note: The template is partially customized.

---------------------------------------------------------------------------

6. Can the following code be compiled? Why?

Class

{

Public:

Virtual ~ A ()

{

}

PRIVATE:

Void operator Delete (void * P );

};

Int main (INT argc, char * argv [])

{

A _ 1;

}

A:

No

Note:

1) if a class has a virtual destructor, the custom delete function must have a function body.

2) in this question, the delete function is not called.

3) For this question, the delete function is not called, but the compiler needs it. Therefore, it cannot be defined.

Refer:

If the object is dynamically created (new), the system first calls the Destructor and then calls the Operator During the delete operation.
Delete. During compilation, the compiler will merge the two steps into a function and read the disassembly code. The function name is similar to 'scalar deleting.
Destructor '. If the operator delete function is declared but not defined, the function address is not obtained during compilation.
The 'scalar deleting destructor' built-in function reports an error.

---------------------------------------------------------------------------

7. What are the differences between C and C ++ static functions?

When the static keyword in C acts on a function, it limits the function scope. The static function scope is limited to the part after the function is defined in the current file.

The global functions of C ++ are modified using static and a meaning in C Language (C ++ Standard suggests that an anonymous namespace should include this function to replace the static keyword ); however, if a class member function uses static modification to indicate the class scope rather than the object scope, it can be referenced directly through the class name.

---------------------------------------------------------------------------

8. Functions of the const function.

Class designers declare functions as const to indicate that they do not modify class objects.

The data member cannot be modified in the const function. (Note that, although in the const function, the pointer member variable cannot be modified, but the modification to the content pointed to by the pointer is allowed ).

A const class object can only call const member functions (except const and destructor ).

---------------------------------------------------------------------------

9. When will the copy constructor be used? What are precautions for implementation?

Several Functions of copying constructors:

1) When initializing another object of the class with one class object:

A;

A B ();

A B =;

2) When assigning a class object to another class object:

A B;

B =;

3) when passing parameters and returning:

A f (a) // The copy constructor is called for passing parameters and returning them.

{

//...

}

Note the following during implementation:

1) when there is a pointer variable member in the class, check whether to directly copy the value of the pointer variable, or re-allocate the memory and then recursively copy the structure.

2) whether each object must have a member variable with a unique value (such as an account ). In fact, 1) can also be classified as 2 ).

---------------------------------------------------------------------------

10. Write the function pointer, return the pointer function, const pointer, pointer to const, and const pointer to const.

Void (* f )()

Void * F ()

Int * const F

Const int * F

Const int * const F

---------------------------------------------------------------------------

11. smart pointer.

A smart pointer is a class that simulates pointer actions. All Smart pointers are reloaded-> and * operators.


Smart pointers also have many other functions, which are useful for automatic destruction. This mainly uses the limited scope of the stack object and the temporary object (limited scope implementation) destructor to release the memory. Of course, smart pointers are not
These include modifying the source object during replication. Smart pointers are designed differently based on requirements (copy upon writing, assign values to release objects with permissions, reference counts, control transfer, etc ). This topic can be
To write a book.

Auto_ptr is a common smart pointer.

Smart pointers are usually implemented using class templates:

Template <class T>

Class smpoint

{

Public:

Smpoint (T * P): _ p (p ){}

T & operator * () {return * _ p ;}

T * operator-> () {return _ p ;}

~ Smpoint () {Delete _ p ;}

PRIVATE:

T * _ P;

}

---------------------------------------------------------------------------

12. How to append data to the vector of the standard template library? Note how the underlying layer is implemented rather than used.

The key point is to determine whether the reserved space meets the requirements before appending objects. If not, allocate sufficient space according to the allocation policy.
(Generally, the square increment policy is used). Copy the previous object array, release the original space, and append the object to the end. If any operation fails, at least the original array is retained.
Full guarantee policy ).

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.